用Iterator實現遍歷集合


使用Collection類的Iterator,可以方便的遍歷Vector, ArrayList, LinkedList等集合元素,避免通過get()方法遍歷時,針對每一種對象單獨進行編碼。

示例:

[java] view plain copy
  1. Collection coll = new Vector(); //LinkedList(); //ArrayList();  
  2. coll.add("Tody");  
  3. coll.add("is");  
  4. coll.add("Sunday.");  
  5.   
  6. // Output all elements by iterator  
  7. Iterator it = coll.iterator();  
  8. while(it.hasNext()) {  
  9.     System.out.print(it.next() + " ");  
  10. }  

輸出:

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

 

[java] view plain copy
  1. Collection coll = new HashSet();  
  2. coll.add("Tody");  
  3. coll.add("is");  
  4. coll.add("Sunday.");  
  5.   
  6. // Output all elements by iterator  
  7. Iterator it = coll.iterator();  
  8. while(it.hasNext()) {  
  9.     System.out.print(it.next() + " ");  
  10. }  

輸出:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM