思路
1、定义学生类
2、创建Collection集合对象
3、创建学生对象
4、把学生添加到集合
5、遍历集合(迭代器遍历)
代码示例
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;
}
}
public static void main(String[] args) {
//创建学生对象
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 19);
Student s3 = new Student("王五", 20);
//创建Collection集合对象
Collection<Student> c = new ArrayList<Student>();
//把学生添加到集合中
c.add(s1);
c.add(s2);
c.add(s3);
//返回集合元素中的迭代器,通过集合Iterator()方法得到
Iterator<Student> it = c.iterator();
//用while循环判断
while (it.hasNext()) {
Student s = it.next();
System.out.println(s.getName()+","+s.getAge());
}
}