ConcurrentModificationException出现的原因

ConcurrentModificationException出现的原因:用Iterator遍历ArrayList时,循环中用ArrayList对象对其自身进行了增删操作。

public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(2);
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer integer = iterator.next();
            if (integer == 2) {
                // list.remove(integer);//执行
                // Exception in thread "main" java.util.ConcurrentModificationException at
                // java.util.ArrayList$Itr.checkForComodification(Unknown Source) at
                // java.util.ArrayList$Itr.next(Unknown Source) at
                // hpe_0801.Test.main(Test.java:14)
                iterator.remove();// 成功删除
            }
        }
    }

异常发生在iterator.next()调用的时候,查看ArrayList类内部迭代器类的源码中的iterator.next(),首先调用checkForComodification()方法,而该方法检查modCount 和 expectedModCount变量是否相等(modCount标记该列表被改动的次数,expectedModCount迭代器内部记录该列表被修改的次数),不相等抛出异常。迭代器的remove()会调用ArrayList的remove()(会更改modCount的值),进行删除。然后,迭代器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;

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

解决方法:
1>只用迭代器删除:

while (iterator.hasNext()) {
        Integer integer = iterator.next();
        if (integer == 2) {
            iterator.remove();
        }
}

2>用CopyOnWriteArrayList/ConcurrentHashMap
3>用普通的循环对,通过列表直接操作

for(int i=0;i<list.size();i++){
    if (list.get(i) == 2) {
            list.remove(i);
        }
}

注意:ArrayList是非线程安全的。
参考:
https://www.javacodegeeks.com/2011/05/avoidconcurrentmodificationexception.html
https://www.2cto.com/kf/201403/286536.html
https://blog.csdn.net/izard999/article/details/6708738
https://www.cnblogs.com/dolphin0520/p/3933551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值