java.util.ConcurrentModificationException 详解

问题出现

这次写代码写的比较急出现的一个问题,在遍历的时候使用Iterator在删除的时候用了List的remove,就出现了java.util.ConcurrentModificationException;

public static void main(String[] args) {
    List<Integer> li=new ArrayList<Integer>(){{add(1);add(1);add(1);add(1);add(1);add(1);add(1);}};
    Iterator<Integer> iterator = li.iterator();
    while (iterator.hasNext()){
        Integer next = iterator.next();
        li.remove(next);
    }
}

原因

看到报错,找到报错原因

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

是因为modCount和expectedModCount不相等,那modCount和expectedModCount是什么呢?

全局找modCount修改地方,发现增删等地方会修改这个计数变量。

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

发现会+这个值,就是修改次数。

那看下expectedModCount又是什么,发现

    /**
     * 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;
        ...
        }

发现在初始化迭代器时expectedModCount等于modCount,但是remove会++那就导致了不相等,为啥不在remove的时候expectedModCount–呢,为啥这样设计呢?大概是设计者不想在迭代的时候,集合去操作,而是交给迭代器,如下:

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

所以删除的时候使用迭代器的方法就行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值