使用Collection類的Iterator,可以方便的遍歷Vector, ArrayList, LinkedList等集合元素,避免通過get()方法遍歷時,針對每一種對象單獨進行編碼。
示例:
- Collection coll = new Vector(); //LinkedList(); //ArrayList();
- coll.add("Tody");
- coll.add("is");
- coll.add("Sunday.");
- // Output all elements by iterator
- Iterator it = coll.iterator();
- while(it.hasNext()) {
- System.out.print(it.next() + " ");
- }
輸出:
Tody is Sunday.
1.hasNext()函數的API解釋
boolean java.util.Iterator.hasNext()
hasNext
boolean hasNext()
-
Returns
trueif the iteration has more elements. (In other words, returnstrueifnext()would return an element rather than throwing an exception.)
- Returns:
-
trueif the iteration has more elements
---------------------------------------------------------
2.next()函數的API解釋
Object java.util.Iterator.next()
next
E next()
-
Returns the next element in the iteration.
-
- Returns:
- the next element in the iteration
- Throws:
-
NoSuchElementException- if the iteration has no more elements
- Collection coll = new HashSet();
- coll.add("Tody");
- coll.add("is");
- coll.add("Sunday.");
- // Output all elements by iterator
- Iterator it = coll.iterator();
- while(it.hasNext()) {
- System.out.print(it.next() + " ");
- }
輸出:
is Sunday. Tody
由上面兩個例子看出,在List和Set對象中,Iterator的next()方法返回的值是不一樣的。
原因是List屬於線性集合,元素是有序的,讀取時是按照數組的形式,一個接一個的讀取,存儲也是按照add的順序添加的。
而Set屬於非線性的,是無序的,所以讀取的元素與添加的順序不一定一致。
對於HashSet,其實它返回的順序是按Hashcode的順序。
如果迭代也有序,則可以用LinkedHashSet。
http://topic.csdn.net/u/20101227/09/63a23d05-7f15-4b0e-9287-e97f96ba4349.html?77188351
