1 import java.util.ArrayList; 2 import java.util.Iterator; 3 4 import cn.itcast.p1.bean.Person; 5 6 public class ArrayListTest { 7 8 public static void main(String[] args) { 9 ArrayList al = new ArrayList(); 10 11 al.add(new Person("lisi1",22)); 12 al.add(new Person("lisi2",23)); 13 al.add(new Person("lisi3",24)); 14 al.add(new Person("lisi4",25)); 15 16 Iterator it = al.iterator(); 17 18 while(it.hasNext()) 19 { 20 // System.out.println(((Person) it.next()).getName()+"--"+((Person) it.next()).getAge()); //結果一 21 //這種方法取出是不對的,如果集合容器的元素個數是單數時,會拋出java.util.NoSuchElementException錯誤 22 23 Person p = (Person) it.next(); 24 25 System.out.println(p.getName()+"--"+p.getAge()); //結果二 26 } 27 28 } 29 30 }