测试类
public class CollectionDemo {
public static void main(String[] args) {
Collection<Student> c=new ArrayList<Student>();
//创建学生对象
Student s1=new Student("阿凡达",30);
Student s2=new Student("小明",20);
Student s3=new Student("小刚",25);
//把学生添加到集合
c.add(s1);
c.add(s2);
c.add(s3);
//遍历集合(迭代器方式)
Iterator<Student> it=c.iterator();
while(it.hasNext()) {
Student s=it.next();
System.out.println(s.getName()+","+s.getAge());
}
}
}
/*
Iterator(迭代器,集合的专用遍历方式)中的常用方法:
next() 返回迭代中的下一个元素
hasNext() 如果迭代具有更多元素,则返回true
*/
学生类
public class Student {
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
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;
}
}