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 +
'}';
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端