爲了利用迭代器模式,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語法來遍歷自定義的類。