Collection 接口的使用

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 +
'}';
}
}



posted @   惊鸿宴远赴人间  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示