看原始碼1. ArrayList中的Iterator實現

weixin_34189116發表於2018-04-25
ArrayList的包裡面的關於 Iterator 的實現原始碼:
/**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // 下一個元素的下標
        int lastRet = -1; // 最後一個返回的下標,如果沒有,返回 -1
        int expectedModCount = modCount;

        Itr() {}//預設的無參構造方法

        public boolean hasNext() {
            return cursor != size;//cursor 未到達線性表的末尾
        }

        @SuppressWarnings("unchecked")
        public E next() {//獲取 list 下一個元素
            checkForComodification();//檢查是否有併發的執行緒對list進行修改
            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++]);//遍歷線性表
            }//在迭代的末尾更新一次,減少堆記憶體的寫入壓力
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {//檢查是否有併發執行緒的修改,如果有就丟擲異常
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

相關文章