1. 程式人生 > >JDK原始碼閱讀——ArrayList(2)

JDK原始碼閱讀——ArrayList(2)

public Iterator<E> iterator() {
    return new Itr();
}
private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        return
cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw
new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1
; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }

iterator()方法新建並返回一個ArrayList的迭代器,該迭代器是個內部類,擴充套件了Iterator< E >介面。迭代器分別使用兩個int型變數cursor和lastRet分別指向下一個返回的元素和最近返回的元素。
迭代器中用得最多的方法是hasNext()和next()。hasNext()將cursor與ArrayList的size進行比較,若相等說明無下一個元素,則返回false,否則返回true;next()首先比較cursor與size,若cursor>=size則丟擲異常,否則返回cursor所指向的元素並將cursor賦給lastRet,然後cursor++。
remove方法則刪除lastRet所指向的元素,即上一個返回的元素,並將lastRet賦給cursor,同時lastRet = -1。