文章目錄
使用Collection類的Iterator,可以方便的遍曆Vector, ArrayList, LinkedList等集合元素,避免通過get()方法遍曆時,針對每一種對象單獨進行編碼。
樣本:
Collection coll = new Vector(); //LinkedList(); //ArrayList();<br />coll.add("Tody");<br />coll.add("is");<br />coll.add("Sunday.");</p><p>// Output all elements by iterator<br />Iterator it = coll.iterator();<br />while(it.hasNext()) {<br />System.out.print(it.next() + " ");<br />}
輸出:
Tody is Sunday.
1.hasNext()函數的API解釋
boolean java.util.Iterator.hasNext()
hasNext
boolean hasNext()
-
Returns
true if the iteration has more elements. (In other words, returns
true if
next() would return an element rather than throwing an exception.)
-
Returns:
-
true if 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();<br />coll.add("Tody");<br />coll.add("is");<br />coll.add("Sunday.");</p><p>// Output all elements by iterator<br />Iterator it = coll.iterator();<br />while(it.hasNext()) {<br />System.out.print(it.next() + " ");<br />}
輸出:
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