1.定义学生类
2.创建Collection集合对象
3.创建学生对象
4.把学生添加到集合
5.遍历集合(迭代器方式)
import java.util.*;
public class Main {
public static void main(String[] args) {
Collection<Student> list=new ArrayList<>();
Student s1 = new Student("刘宇航",12);
Student s2 = new Student("刘宇",13);
Student s3 = new Student("刘",14);
list.add(s1);
list.add(s2);
list.add(s3);
Iterator<Student> it=list.iterator();
for(;it.hasNext();)
{
Student str = it.next();
System.out.println(str.getName()+","+str.getAge());
}
}
}
class Student{
String name;
int age;
public Student(String name,int age){
this.age=age;
this.name=name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
运行结果
刘宇航,12
刘宇,13
刘,14