集合forEach删除元素抛出ConcurrentModific

2019-02-12  本文已影响0人  蜗牛写java

集合forEach删除元素抛出ConcurrentModificationException

案例

​ 代码

public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        for (String str : list) {
            list.remove(str);
        }
    }

​ 输出

Exception in thread "main" java.util.ConcurrentModificationException
​ at java.util.ArrayListItr.checkForComodification(ArrayList.java:901) ​ at java.util.ArrayListItr.next(ArrayList.java:851)
​ at com.dwb.java.collection.deleteElement.DeleteElement1.main(DeleteElement1.java:14)

Process finished with exit code 1

原因分析

​ forEach循环使用场景必须是数组或者实现Iterable接口的容器类;该循环使用了Iterator的hasNext()和next()两个方法,ArrayList 中有一个修改元素计数标记modCount,ArrayList中的迭代器实现类也有一个修改元素计数标记expectedModCount,每次循环都需要调用hasNext 和 next方法,调用next方法前,就要比较modCount 和 expectedModCount是否相等,若不等则抛出ConcurrentModificationException异常。以上例子中forEach中调用了ArrayList的remove方法,这时候modCount做了改变;但是迭代器中的expectedModCount没有改变,所以两者不等,抛出异常。

源码分析

​ ArrayList源码中迭代器的实现类

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++]);
            }
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            //修改元素计数标记 比较 ;该处为上例子中抛出异常的源头
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

forEach介绍

Iterator介绍

一种迭代器模式

正确集合循环删除元素方式

​ 正确的方式为,迭代器中删除

public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            //取出元素;做逻辑
            String element = iterator.next();
            //删除该元素
            iterator.remove();
        }
        System.out.println(list.size());
    }

​ 输出

0

为什么该方式可以正常删除元素?

以ArrayList中Iterator实现类中的remove方法源码为例

public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException();
    checkForComodification();

    try {
        //实际上也是调用remove方法
        ArrayList.this.remove(lastRet);
        cursor = lastRet;
        lastRet = -1;
        //删除元素后,重置expectedModCount 为 modCount;该步是关键
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}

for循环删除元素(错误方式)

public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        for (int i = 0; i < list.size(); i++) {
            list.remove(i);
        }
        System.out.println(list);
    }

​ 输出

[2,4]

错误分析

​ 该方式为下边删除元素,删除元素后,list大小有改变,下标也是对应改变

​ 第一次循环:i=0; i<list.size(4); 集合[1,2,3,4]; 要删除的元素list[0]; 删除后集合[2,3,4]; list.size = 3

​ 第二次循环:i=1; i<list.size(3);集合[2,3,4]; 要删除的元素list[1]; 删除后集合[2,4]; list.size = 2

​ 第三次循环:i=2; i<list.size(2) 不成立,循环结束

总结

上一篇 下一篇

猜你喜欢

热点阅读