用Iterator實現遍曆集合

來源:互聯網
上載者:User
文章目錄
  • hasNext
  • next

使用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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.