for-each或迭代器中调用List的remove方法会抛出ConcurrentModificationException的原因

版权声明:转载请注明 https://blog.csdn.net/qq_34115899/article/details/81978660

for-each循环遍历的实质是迭代器,使用迭代器的remove方法前必须调用一下next()方法,并且调用一次next()方法后是不允许多次调用remove方法的,为什么呢?接下来一起来看吧

    public void remove(ArrayList<Integer> list) {
        for (Integer integer : list) {
            if (integer == 5) {
                list.remove(integer);
            }
        }
    }

比如这一段代码会抛出ConcurrentModificationException,为什么呢,请看源码

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

    /**
     * An optimized version of AbstractList.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();
        }
    }

实质是变化为迭代器实现,不管是迭代器里面的remove()还是next()方法,都会checkForComodification();而这个方法是判断modCount和expectedModCount是否相等,这个modCount是这个list集合修改的次数,每一次add或者remove都会增加这个变量

然后迭代器每次去next或者去remove的时候检查checkForComodification();发现expectedModCount(这个迭代器修改的次数)和modCount(这个集合实际修改的次数)不相等,就会抛出ConcurrentModificationException

迭代器里面没有add方法,用迭代器时,可以删除原来集合的元素,但是!一定要用迭代器的remove方法而不是集合自身的remove方法,否则抛异常。

再来看一个例子,这个是否正确?

public void remove(ArrayList<Integer> list) {
    Iterator<Integer> it = list.iterator();
    while (it.hasNext()) {
        it.remove();
    }
}

这个第一次循环就会抛出IllegalStateException异常,为什么呢?那么我们再次看到迭代的remove方法

关于lastRet,我们后面再讲,来看看,上一次remove()之后,lastRet变成了-1,然后没有it.next();继续执行remove(),首先判断if(lastRet<0)的时候就抛出了这个IllegalStateException异常。所以刚刚的代码是错的。

为什么要it.next()?难道next()方法又改了lastRet吗?它确确实实更改了。

 lastRet被赋值为i就不是-1了,下一次需要remove的时候就不会抛出IllegalStateException

那再来看看这个相同原理的例子

public void remove(ArrayList<Integer> list) {
    Iterator<Integer> it = list.iterator();
    while (it.hasNext()) {
        it.next();
        it.remove();
        it.remove();
    }
}

这个正确吗?刚刚已经说了这个是错误的会抛出IllegalStateException异常,因为remove()调用一次后lastRet会变成-1,第二个remove()在第一句if(lastRet<0)的时候就异常了。

正确的使用:

public void remove(ArrayList<Integer> list) {
    Iterator<Integer> it = list.iterator();
    while (it.hasNext()) {
        it.next();
        it.remove();
    }
}

这里可不允许it.next()和it.remove()顺序交换!

因为lastRet的值初始化是-1,所以如果先remove()就会抛出IllegalStateException异常。

综上

1.在for-each循环和迭代器中只可以做删除remove操作,不能做添加add操作。想要删除集合中的元素必须用迭代器的remove方法,不能添加操作add,因为add也会修改集合的modCount导致ConcurrentModificationException

2.用迭代器的remove()前必须调用一下next()方法,否则IllegalStateException

3.调用一次next()方法后是不允许多次调用remove方法,否则IllegalStateException

=========================Talk is cheap, show me the code========================

猜你喜欢

转载自blog.csdn.net/qq_34115899/article/details/81978660