package collectionStudy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection的使用:保存学生信息
* @create 2021-02-25 9:21
*/
public class Demo02 {
public static void main(String[] args) {
//新建Collection对象
Collection collection=new ArrayList();
Student s1 = new Student("张三",20);
Student s2 = new Student("罗斯",22);
Student s3 = new Student("王二",10);
//1添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println("元素个数:"+collection.size());
System.out.println(collection.toString());
//2删除
collection.remove(s1);
System.out.println("删除之后:"+collection.size());
//3遍历
//3.1增强for
System.out.println("-------增强for-------");
for (Object object:collection
) {Student s=(Student) object;
System.out.println(s.toString());
}
//3.2迭代器:hasNext();next();remove();迭代过程中不能使用collection的删除方法
System.out.println("-------迭代器-------");
Iterator it =collection.iterator();
while (it.hasNext()){
Student s=(Student)it.next();
System.out.println(s.toString());
}
//4判断
System.out.println(collection.contains(s2));
System.out.println(collection.isEmpty());
}
}
学生类
package collectionStudy;
/**
* 学生类
* @create 2021-02-25 9:21
*/
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}