Iterator和Iterable接口

迭代器模式本質是將聚合對象的內容與遍歷分開,所以使用者可以不用考慮聚合對象的底層實現(是用list存儲還是用數組存儲)而以一種統一的方式(Iterator)來遍歷對象;而且可以利用篩選迭代器對對象進行過濾,只遍歷符合條件的對象;迭代器的迭代策略(單向、雙向等)可以靈活的修改。

爲了利用迭代器模式,java中定義了一個Iterator迭代器接口和一個Iterable接口;Iterator迭代器中定義了遍歷需要用到的方法,如next()、hasNext()、remove()方法;Iterable接口中聲明瞭一個Iterator迭代器;

Iterator接口定義在java.util包中:
public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove();
}

實現Iterator接口的接口和類如下所示:
所有已知子接口:
ListIterator<E>, XMLEventReader
所有已知實現類:
BeanContextSupport.BCSIterator, EventReaderDelegate, Scanner

其中ListIterator接口在Iterable接口的基礎上增加了前向遍歷的方式,定義如下:
public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext();
    E next();
    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void remove();
    void set(E e);
    void add(E e);
}


Iterable接口定義在java.lang包中:
public interface Iterable<T> {
    Iterator<T> iterator();
}

實現了Iterable接口的接口和類如下:
所有已知子接口:
BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Collection<E>, Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>, SortedSet<E>
所有已知實現類:
AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue,
ArrayDeque, ArrayList, AttributeList, BatchUpdateException, BeanContextServicesSupport, BeanContextSupport,
 ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DataTruncation, 
DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet,
 LinkedList, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, RowSetWarning, SerialException,
 ServiceLoader, SQLClientInfoException, SQLDataException, SQLException, SQLFeatureNotSupportedException,
SQLIntegrityConstraintViolationException, SQLInvalidAuthorizationSpecException, SQLNonTransientConnectionException
, SQLNonTransientException, SQLRecoverableException, SQLSyntaxErrorException, SQLTimeoutException,
SQLTransactionRollbackException, SQLTransientConnectionException, SQLTransientException, SQLWarning, 
Stack, SyncFactoryException, SynchronousQueue, SyncProviderException, TreeSet, Vector

Collection接口繼承了Iterable接口:(注意Collection是一個接口,而Collections是一個操作集合的工具類)
public interface Collection<E> extends Iterable<E> {}
Collection的幾個子接口,如List、Set、Queue也都間接繼承了Iterable接口。
Map接口沒有繼承Iteratale接口,但是Map的遍歷訪問可以通過獲取Map的KeySet(keySet是一個set集合)來遍歷Map。
public interface Map<K,V> {}

可以看出所有的集合類都是直接或間接繼承了Iterable接口的,而Iterable接口中可以獲得Iterator迭代器,這樣保證了每個集合類的每個副本每次獲得的Iterator都是從第一個元素開始遍歷的,各個Iterator互不干擾。

另外,foreach的實現原理是編譯器幫我們將遍歷直接轉換成了對集合iterator.next()的調用(可以使用foreach進行遍歷集合都實現了Iterable接口),所以如果自定義類實現了Iterable接口並且實現了該接口中iterator()方法的具體定義,則可以通過foreach語法來遍歷自定義的類



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章