ArrayListソースコード分析2

主にフェイルファストメカニズムについて話します。
フェイルファストメカニズムは、コレクションを反復するときにコレクションの構造を変更できないイテレータです。変更すると、エラーが報告されます。ConcurrentModificationExceptionConcurrentModificationException。

private class Itr implements Iterator<E> {
    
    
        int cursor;       // 返回下一个元素的位置
        int lastRet = -1; // 返回最后一个元素的位置。-1表示没有
        //expectedModCount 是期望值。也就是集合的期望修改的值。ArrayList每次元素增加或者减少都会变化modCount。
        int expectedModCount = modCount;

        // prevent creating a synthetic constructor
        Itr() {
    
    }

        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
        public void forEachRemaining(Consumer<? super E> action) {
    
    
            Objects.requireNonNull(action);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i < size) {
    
    
                final Object[] es = elementData;
                if (i >= es.length)
                    throw new ConcurrentModificationException();
                for (; i < size && modCount == expectedModCount; i++)
                    action.accept(elementAt(es, i));
                // update once at end to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }
		//检查如果modCount!=expectedModCount。就开始抛出异常
        final void checkForComodification() {
    
    
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/GoSaint/article/details/113884382