为什么java不要在foreach循环里进行元素的remove/add操作

为什么java不要在foreach循环里进行元素的remove/add操作

在这里插入图片描述
首先结论是“1”不会报错,但是“2“会出现ConcurrentModificationException(当方法检测到对象的并发修改,但不允许这种修改时就抛出该异常)。在这里插入图片描述
从上面我们可以知道是checkForComodification出现的异常,看一下源码

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

也就是因为 modCount != expectedModCount,modCount是ArrayList的一个变量,那modCount是什么时候改变的呢?其实是在list.remove()改变的,remove()里面会调用fastRemove(int)方法

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; // clear to let GC do its work
    }

上面我们可以看到,因为删除了一个元素,所以modCount+1,造成modCount != expectedModCount,从而抛出异常。

至于为什么删除“1”就可以呢,原因在于foreach和迭代器的hasNext()和next()方法,foreach这个语法糖,编译后实际上就是

while(itr.hasNext()){
    itr.next()
}

所以每次循环都会先执行hasNext(),那么看看ArrayList的hasNext()是怎么写的:

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

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

Itr是ArrayList的内部类,调用ArrayList.hasNext()实际上调用的是Itr,hasNext(),cursor是用于标记迭代器位置的变量,该变量由0开始,每次在next()方法里面执行+1操作,一开始cursor=0, size=2, hasNext()为true, 于是进入next()方法,cursor+1, 在你的代码在执行删除“1”后,size=1,cursor=1,此时hasNext()返回false,结束循环,因此你的迭代器并没有调用next()查找第二个元素, checkForComodification()方法是在next()方法里面执行的, 所以也就无从检测modCount是否改变了,因此也不会出异常。

对于”2“这种情况,一开始cursor=0, size=2, hasNext()为true, 于是进入next()方法,cursor+1,但是
if (“2”.equals(intem))不成立,继续循环 ,cursor=1, size=2,hasNext()为true, 于是进入next()方法,cursor+1,if (“2”.equals(intem))成立,会删除“2”,删除时modCount+1,此时size=1,cursor=2,hasNext()返回true,于是迭代就又去调用了一次next(),在checkForComodification()方法中发现modCount改变了,就会抛ConcurrentModificationException异常。

你可以试一下,当你的集合有三个元素的时候,你就会神奇的发现,删除“1”是会抛出异常的,但删除“2”就没有问题了,你可以按照上面的源码自己分析,这里不在赘述。

那么我们应该怎么在迭代时删除元素呢?使用Iterator的方式。

在这里插入图片描述为什么使用Iterator的方式就不会有ConcurrentModificationException异常呢?
因为Iterato iterator = list.iterator() ; 这个方法的实现就是返回上面说过的内部类 Itr,看一下源码:

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

然后我们看一下iterator.remove()的源码;

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

看源码我们可以知道 ArrayList.this.remove 之前进行的 checkForComodfication 检查,remove 之后又使 expectedModCount = modCount,所以不会在next()再次检查的时候出现错误。

但是要注意的时多线程的情况下要对iterator对象加锁,因为假如线程1执行了 ArrayList.this.remove 后,还没将expectedModCount 设置为 modCount的值,线程2这个时候进行checkForComodification()的时候就会抛出异常。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值