Interface Collection:Collection是个接口
用接口的引用指向实现类对象
//以多态的形式创建集合对象,调用单例集合中的共有方法
Collection<String> collection= new ArrayList<>();
Collection的常用方法:
方法 | 描述 |
---|---|
add(E e) | 确保此集合包含指定的元素 |
clear() | 从此集合中删除所有元素 |
contains(Object o) | 如果此集合包含指定的元素,则返回 true |
isEmpty() | 如果此集合不包含元素,则返回 true |
remove(Object o) | 从该集合中删除指定元素的单个实例(如果存在) |
int size() | 返回此集合中的元素数 |
public class CollectionTest1 {
public static void main(String[] args) {
//以多态的形式创建集合对象,调用单例集合中的共有方法
Collection<String> collection= new ArrayList<>();
collection.add("张三");
collection.add("李四");
collection.add("王五");
System.out.println(collection.isEmpty());
System.out.println(collection);
System.out.println("-------------------");
//remove这里要注意,再根据对象做删除的时候,得重写equals方法
//如果没有重写,因为equals比较的是地址,就无法删除
Collection<Student> c=new ArrayList<>();
c.add(new Student("张三",18));
c.add(new Student("李四",22));
c.add(new Student("王五",25));
c.remove(new Student("李四",22));
System.out.println(c);
collection.remove("李四");
System.out.println(collection);
System.out.println("-------------------------");
collection.clear();
System.out.println(collection);
}
}
Student类:
//没沾全,右键generate自动生成
public class Student {
private String name;
private int age;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
未重写equals方法的结果:
false
[张三, 李四, 王五]
-------------------
[Student{name = 张三, age = 18}, Student{name = 李四, age = 22}, Student{name = 王五, age = 25}]
[张三, 王五]
-------------------------
[]
重写equals方法的结果:
false
[张三, 李四, 王五]
-------------------
[Student{name = 张三, age = 18}, Student{name = 王五, age = 25}]
[张三, 王五]
-------------------------
[]
contains方法在这同理,如果没有重写equals方法,返回结果就不同,remove和contains方法底层都依赖于equals方法来进行操作。