import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo01 {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("张三",16);
Student s2 = new Student("李四",17);
Student s3 = new Student("王五",18);
//1.添加元素
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println(collection);//[Student{name='张三', age=16}, Student{name='李四', age=17}, Student{name='王五', age=18}]
System.out.println(collection.size());//3
//2.删除元素
collection.remove(s1);
System.out.println(collection);
System.out.println(collection.size());//2
//3.遍历元素
//1.增强for
for (Object object:
collection) {
Student s=(Student) object;
System.out.println(s);
}
//2.迭代器
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
Object next = iterator.next();
Student s = (Student) next;
System.out.println(s);
}
//4.判断
System.out.println(collection.contains(s2));//true
System.out.println(collection.isEmpty());//false
}
}
public class Student {
private String name;
private int age;
public Student() {
}
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 +
'}';
}
}