ArrayList source code analysis 2

Mainly talk about the fail-fast mechanism.
The fail-fast mechanism is an iterator that does not allow changes to the structure of the collection when iterating the collection. If it changes, it will report an error. Concurrent ModificationException ConcurrentModificationException.

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();
        }
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/GoSaint/article/details/113884382