[ConcurrentModificationException]关于对Map、List等集合操作抛出ConcurrentModificationException 异常问题

本文详细分析了Java中在并发环境下对List、Map等集合进行迭代操作时抛出`ConcurrentModificationException`的原因,源码解析了ArrayList的Itr类中的迭代逻辑。在单线程环境中,推荐使用迭代器的`remove()`方法或避免在遍历过程中修改集合。然而,在多线程场景下,`CopyOnWriteArrayList`和`ConcurrentHashMap`等并发友好的集合类成为更好的选择。文章还探讨了`CopyOnWriteArrayList`的限制及其使用注意事项,并指出在多线程环境下,只有使用`CopyOnWriteArrayList`才能避免并发修改异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

  • 先上代码:

  • 会报一下错:

分析原因:

  • 从报错原因可以看到,首先是checkForComodification()方法异常,然后抛给next()方法。
  • 所以我们查看结合程序查看源码:
ArrayList源码:
 public Iterator<E> iterator() {
        return new Itr();
 }
 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;
  }
  public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    /*
     * Private remove method that skips bounds checking and does
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值