在java的集合中,List接口繼承Collection接口,AbstractList類實現了List接口,在AbstractList中的內部類Itr實現了Iterator接口
ArrayList實現List接口並繼承AbstractList類,結構圖如下:(圖片出自網絡)
Iterator接口源碼:
public interface Iterator<E> { boolean hasNext(); E next(); default void remove() { throw new UnsupportedOperationException("remove"); } default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
AbstractList的內部類Itr實現了Iterator接口,如下所示:
private class Itr implements Iterator<E> { /**元素的下標 * Index of element to be returned by subsequent call to next. */ int cursor = 0; /**上一個元素的下標。如果元素已被刪除就設置為-1 * Index of element returned by most recent call to next or * previous. Reset to -1 if this element is deleted by a call * to remove. */ int lastRet = -1; /**允許修改的次數,違規操作會拋異常 * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. */ int expectedModCount = modCount; /*檢查是否還有下一個元素*/ public boolean hasNext() { return cursor != size(); } /*光標下移,並且返回當前的元素*/ public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } /*移除元素*/ public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
ArrayList中的iterator()方法:
public Iterator<E> iterator() { return new Itr(); }
ArrayList中的內部類Itr源碼功能類似於AbstractList的內部類Itr。
閱讀了Iterator的源碼,再回頭看Iterator遍歷List的過程,理解就會深刻很多。
List<String> list=new ArrayList<String>(); list.add("apple"); list.add("banana"); list.add("watermelon"); for (Iterator<String> iterator=list.iterator();iterator.hasNext();) { System.out.println( iterator.next());
}