天天看點

Iterator、Iterable接口的使用及詳解

Java集合類庫将集合的接口與實作分離。同樣的接口,可以有不同的實作。

Java集合類的基本接口是Collection接口。而Collection接口必須繼承java.lang.Iterable接口。

以下圖表示集合架構的接口,java.lang以及java.util兩個包裡的。其他部分可以從左向右看,比如Collection的Subinterfaces有List,Set以及Queue等。

Iterator、Iterable接口的使用及詳解

以下例子是利用了Iterator接口的着三個方法,實作周遊ArrayList<String>類型。

一開始疊代器在所有元素的左邊,調用next()之後,疊代器移到第一個和第二個元素之間,next()方法傳回疊代器剛剛經過的元素。

hasNext()若傳回True,則表明接下來還有元素,疊代器不在尾部。

remove()方法必須和next方法一起使用,功能是去除剛剛next方法傳回的元素。

for-each循環可以與任何實作了Iterable接口的對象一起工作。

而java.util.Collection接口繼承java.lang.Iterable,故标準類庫中的任何集合都可以使用for-each循環。

此接口的方法

public interface Collection<E>{......}

Modifier and Type

Method and Description

<code>boolean</code>

Ensures that this collection contains the specified element (optional operation).

Adds all of the elements in the specified collection to this collection (optional operation).

<code>void</code>

Removes all of the elements from this collection (optional operation).

Returns true if this collection contains the specified element.

Returns true if this collection contains all of the elements in the specified collection.

Compares the specified object with this collection for equality.

<code>int</code>

Returns the hash code value for this collection.

Returns true if this collection contains no elements.

Returns an iterator over the elements in this collection.

Removes a single instance of the specified element from this collection, if it is present (optional operation).

Removes all of this collection's elements that are also contained in the specified collection (optional operation).

Retains only the elements in this collection that are contained in the specified collection (optional operation).

Returns the number of elements in this collection.

Returns an array containing all of the elements in this collection.

<code>&lt;T&gt; T[]</code>

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

因為其中有一個傳回值為Iterator&lt;E&gt;類型的iterator()方法,是以,java.util.Collection接口必須繼承java.lang.Iterable接口

實作Collection接口的每一個類都要實作以上衆多方法,但開發者自己實作很麻煩。是以java提供了AbstractCollection類來編寫具體的類。

<dl></dl>

<dt></dt>

All Superinterfaces:

<dd></dd>

All Known Subinterfaces:

All Known Implementing Classes:

Collection接口有三個常用的子接口,分别是List,Set,Queue。

http://blog.csdn.net/xujinsmile/article/details/8543544

為什麼一定要去實作Iterable這個接口呢? 為什麼不直接實作Iterator接口呢?

看一下JDK中的集合類,比如List一族或者Set一族,

都是繼承了Iterable接口,但并不直接繼承Iterator接口。

仔細想一下這麼做是有道理的。因為Iterator接口的核心方法next()或者hasNext()

是依賴于疊代器的目前疊代位置的。

如果Collection直接繼承Iterator接口,勢必導緻集合對象中包含目前疊代位置的資料(指針)。

當集合在不同方法間被傳遞時,由于目前疊代位置不可預置,那麼next()方法的結果會變成不可預知。

除非再為Iterator接口添加一個reset()方法,用來重置目前疊代位置。

但即時這樣,Collection也隻能同時存在一個目前疊代位置。

而Iterable則不然,每次調用都會傳回一個從頭開始計數的疊代器。

多個疊代器是互不幹擾的。

http://www.cnblogs.com/highriver/archive/2011/07/27/2077913.html