2.2.2.Collection接口
Collection父接口
- 特点: 代表一组任意类型的对象,无序、无下标、不能重复
- 方法
- boolean add(Object obj) // 添加一个对象
- boolean addAll(Collection c) // 将一个集合中的所有对象添加到此结合中
- void clear() // 清空此集合中的所有对象
- boolean contains(Object o) //检查此集合中是否包含o对象
- boolean equals(Object o) // 比较此集合是否与指定对象相等
- boolean isEmpty() // 判断此集合是否为空
- boolean remove(Object o) // 在此集合中移除o对象
- int size() // 返回此集合中的元素个数
- Object[] toArray() // 将此集合转换成数组
public class demo {
public static void main(String[] args) {
// 创建集合
Collection collection = new ArrayList();
// 添加元素
collection.add("西瓜");
collection.add("苹果");
collection.add("榴莲");
System.out.println(collection.size());
System.out.println(collection);
// 删除元素
collection.remove("榴莲");
//collection.clear();
System.out.println("删除之后:" + collection.size());
// 遍历元素
//// 增强for
for (Object object: collection) {
System.out.println(object);
}
// 使用迭代器
Iterator it = collection.iterator();
while (it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
// 不能使用collection的删除方法
// collection.remove(s)
it.remove();
}
System.out.println("元素个数:" + collection.size());
// 判断
System.out.println(collection.contains("西瓜"));
System.out.println(collection.isEmpty());
// 2
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
// 创建collection对象
Collection collection1 = new ArrayList();
Student s1 = new Student("张三", 10);
Student s2 = new Student("李四", 11);
Student s3 = new Student("王五", 12);
// 添加数据
collection1.add(s1);
collection1.add(s2);
collection1.add(s3);
System.out.println("元素个数:" + collection1.size());
System.out.println(collection1.toString());
// 删除
collection1.remove(s1);
collection1.remove(new Student("王五", 12));
// collection1.clear();
System.out.println("删除之后:"+collection1.size());
// 遍历
for (Object object: collection1) {
Student s = (Student) object;
System.out.println(s.toString());
}
Iterator it1 = collection1.iterator();
while (it1.hasNext()) {
Student s = (Student)it1.next();
System.out.println(s.toString());
}
// 判断
System.out.println(collection1.contains(s1));
System.out.println(collection1.contains(s2));
}
}