ArrayList源碼分析(着重迭代器安全刪除)

ArrayList是我們最常用的集合類型之一,大家都知道他的底層實現是數組。最近剛好想研究一下jdk的源碼,就從ArrayList開始看吧。
本來我想寫的 但是我看完源碼在查資料的時候發現 這個老哥寫的很好,跟我的想法很像,下面貼出鏈接
https://blog.csdn.net/starexplode/article/details/80469079
他有些地方沒寫全 我這裏補充一下
比如迭代器是如何實現安全的循環刪除的

public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor; // 當前操作的數組索引
        int lastRet = -1; // 上次操作的數組索引
        int expectedModCount = modCount;
        //如果當前操作索引==數組size 說明沒有next了
        public boolean hasNext() {
            return cursor != size;
        }
        
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor; //第一次這裏是0,i記錄當前操作的索引
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1; //當前操作的值變爲下一個,保證next獲取的是下個索引的值。
            return (E) elementData[lastRet = i]; //將上一個操作的值變爲i並取出當前操作的值
        }
        /**
        * arrayList的remove其實就是將索引後的所有值向前挪了一位,這時如果能記錄到索引值和後一位的值就能安全的循環刪除了
        */
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet); //由於next()之後才remove() lastRet就是當前next()獲取的值 ,所以直接刪除
                cursor = lastRet; // 將當前操作值 賦值成上次操作的值,這樣就保證了下次next()操作的是remove前的索引
                lastRet = -1; //重新將lastRet賦值爲-1 防止直接再次調用remove() 只能在next()後調用remove()
                expectedModCount = modCount; //由於remove會導致modCount++ 這裏爲了保證這兩個值相等。
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        /**
        * 這個方法可以在 next()到想要的結果之後對剩餘的部分迭代 執行相同的操作,1.8新增,可以在特殊場景減少迭代次數。
        */
        @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();
        }
    }

還有一個是ListItr 這個類是繼承自ArrayList的Itr 並且實現了ListIterator接口的 而ListIterator又是繼承自Iterator的所以他只要實現ListIterator的幾個獨有方法就可以了。

private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();//直接調用父類的構造
            cursor = index;
        }
        //如果當前索引不爲0  就表示前面還有索引
        public boolean hasPrevious() {
            return cursor != 0;
        }
        //操作的下一個結果
        public int nextIndex() {
            return cursor;
        }
        //上一個索引 可能爲負
        public int previousIndex() {
            return cursor - 1;
        }
        //實現思路和next 類似 這裏不再贅述
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1; 
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }next()的值賦值,解決了迭代器中無法修改值得問題
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        //甚至可以add()
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

之後還有一個SubList 這裏相當於是一個內部類 控制的是 一個this的子集 ,裏面有list的基本操作。這裏不再贅述 很簡單。
最後是jdk1.8新加的Spliterator 繼續放老哥的文檔
https://blog.csdn.net/starexplode/article/details/80567758
寫的很棒。

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