ConcurrentModificationException异常原因

本文详细解析了Java集合操作中遇到的ConcurrentModificationException异常,通过源码分析,解释了该异常产生的原因及如何避免。同时探讨了集合清空操作的正确方法,确保代码的稳定性和效率。

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

首先举ConcurrentModificationException的例子:

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


运行结果:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at qunaer.One.main(One.java:20)

运行的错误提示是ConcurrentModificationException,那么为什么会出现这个错误呢?我们通过ArrayList的源码来看看出现异常的原因。

首先上面的程序作了这些操作:remove。那么我们先看看remove的源码:

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

里面有个操作,fastRemove,看源码;

  private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }

首先有个modCount加1。

然后增强for循环遍历集合,底层也是调用的迭代器,集合里有个iterator的方法,返回一个内部类的实例:

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


Itr中有以下内容:

private class Itr implements Iterator<E> {
    int cursor = 0;
    int lastRet = -1;
    int expectedModCount = modCount;
    public boolean hasNext() {
           return cursor != size();
    }
    public E next() {
           checkForComodification();
        try {
        E next = get(cursor);
        lastRet = cursor++;
        return next;
        catch (IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
        }
    }
    public void remove() {
        if (lastRet == -1)
        throw new IllegalStateException();
           checkForComodification();
 
        try {
        AbstractList.this.remove(lastRet);
        if (lastRet < cursor)
            cursor--;
        lastRet = -1;
        expectedModCount = modCount;
        catch (IndexOutOfBoundsException e) {
        throw new ConcurrentModificationException();
        }
    }
 
    final void checkForComodification() {
        if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    }
}

   首先我们看一下它的几个成员变量:

  cursor:表示下一个要访问的元素的索引,从next()方法的具体实现就可看出

  lastRet:表示上一个访问的元素的索引

  expectedModCount:表示对ArrayList修改次数的期望值,它的初始值为modCount。

  modCount是AbstractList类中的一个成员变量

里面有个checkForComodification方法,就是判断是否有更改的。

当使用list中的remove方法时,并没有更改expectedModCount ,而迭代器中是有更改的,所以如果没有改的话就会报错咯,而且还有一个有意思的地方,你有没有想过如何清空一个集合呢?

看看下面的方法行不行?

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

猜对了,不行,大家自己想想为什么,如果不行,是为什么呢?哈哈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值