List系列集合:添加的元素是有序、可重复、有索引的。
Set系列集合:添加的元素是无序、不重复、无索引的。
代码:
public class A01_CollectionDemo1 {public static void main(String[] args) {/** 注意点:Collection是一个接口,我们不能直接创建他的对象。所以,为了学习他的方法,只能创建他实现类的对象实现类:ArrayList*///目的:为了学习Collection接口里的方法Collection<String> coll = new ArrayList<>();//1.添加元素coll.add("aaa");coll.add("bbb");coll.add("ccc");System.out.println(coll);//2..清空//coll.clear();//System.out.println(coll);//3.删除System.out.println(coll.remove("aaa"));System.out.println(coll);//4.判断元素是否包含System.out.println(coll.contains("bbb"));//5.判断集合是否为空System.out.println(coll.isEmpty());//6.返回集合长度System.out.println(coll.size());} }
细节:
1.添加元素:
细节1:如果我们要往List系列集合中添加数据,那么方法永远返回true,因为List系列是允许元素重复的。
细节2:如果我们要往List系列集合中添加数据,如果当前添加的元素不存在,方法返回true,表示添加成功;如果当前要添加的元素已经存在,方法返回false,表示添加失败。因为Set系列的集合不允许重复。
2.删除:
细节1:因为Collection 里面定义的是共性的方法,所以此时不能通过索引进行删除。只能通过元素的对象进行删除。
细节2:方法会有一个布尔类型的返回值,删除成功返回true,删除失败返回false。如果要删除的元素不存在,就会删除失败。
3.判断元素是否包含
细节:底层是依赖equals方法进行判断是否存在的。所以,如果集合中存储的是自定义对象,也想通过contains方法来判断是否包含,那么在javabean类中,一定要重写equals方法。
public class Student {private String name;private int age;public Student(String name) {this.name = name;}public Student(int age) {this.age = age;}public Student(String name,int age){this.name = name;this.age = age;}@Overridepublic boolean equals(Object o) {if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return age == student.age && Objects.equals(name, student.name);}}
public class A02_CollectionDemo2 {public static void main(String[] args) {//1.创建集合的对象Collection<Student> coll = new ArrayList<>();//2.创建三个学生对象Student s1 = new Student("zhangsan", 24);Student s2 = new Student("lis", 25);Student s3 = new Student("wangwu", 26);//3.添加coll.add(s1);coll.add(s2);coll.add(s3);//4.判断集合中某一个学生对象是否包含//因为contains,方法在底层依赖equals方法判断对象是否一一致的。//如果存的是自定义对象,没有重写equals方法,那么默认使用object类中的equals方法进行判断,而object 类中equals方法,依赖地址值进行判断。//需求:如果同姓名和同年龄,就认为是同一 一个学生。//所以,需要在自定义的Javabean类中,重写equals方法就可以了Student s4 = new Student("zhangsan",24);System.out.println(coll.contains(s4));//如果Student中没有equals方法就会返回false} }