1. 程式人生 > 其它 >集合框架-迭代器的使用及原理

集合框架-迭代器的使用及原理

 1 package cn.itcast.p3.collection.demo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 public class IteratorDemo {
 8 
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         Collection coll = new
ArrayList(); 12 coll.add("abc1"); 13 coll.add("abc2"); 14 coll.add("abc3"); 15 coll.add("abc4"); 16 17 //使用了Collection中的iterator()方法。呼叫集合中的迭代器方法,是為了獲取集合中的迭代器物件。 18 // Iterator it = coll.iterator(); 19 // 20 // while(it.hasNext()) { 21 // System.out.println(it.next());
//迴圈後it還能用 22 // } 23 //it.next(); 24 for (Iterator it = coll.iterator(); it.hasNext();) {//一般開發寫這個,迴圈後it不能用 25 System.out.println(it.next()); 26 27 } 28 29 // System.out.println(it.next()); 30 // System.out.println(it.next()); 31 // System.out.println(it.next());
32 // System.out.println(it.next()); 33 // System.out.println(it.next());//java.util.NoSuchElementException 34 35 36 37 38 } 39 40 }
View Code