import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo {
public static void main(String[] args) {
// 创建集合对象
Collection c = new ArrayList();
// 创建元素对象
Student s1 = new Student("zhangsan", 20);
Student s2 = new Student("lisi", 18);
Student s3 = new Student("wangwu", 19);
// 添加元素
c.add(s1);
c.add(s2);
c.add(s3);
// 遍历元素
Iterator it = c.iterator();
while (it.hasNext()) {
Student s = (Student) it.next();
System.out.println(s.getName() + "***" + s.getAge());
}
System.out.println("***********************************");
it = c.iterator();
while (it.hasNext()) {
System.out.println(((Student) (it.next())).getName() + "***"+ ((Student) (it.next())).getAge());
}
}
}
//----------------------------------------------------------------------------------------------------------------------------------
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;
}
}
这个异常代表是无元素异常,迭代器直接往下读,所以读出来的依次是第一个元素的name,第二个元素的age,第三个元素的name,第四个元素的age,而没有第四个元素,所以出现异常
注意:迭代的过程中最好只用一次next()方法 |