美文网首页
for in 循环中remove()抛出ConcurrentMo

for in 循环中remove()抛出ConcurrentMo

作者: zhangxt456 | 来源:发表于2020-11-13 17:04 被阅读0次
    名词说明:

    Itr:集合ArrayList的内部类Itr(迭代器Iterator<E>接口的实现)

    清单 1.for循环中调用ArrayList的和remove()
    List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    for (String s : list) {
        list.add("3");
        if ("2".equals(s)) {
            list.remove(s);
        }
    }
    
    清单 2.Itr的hasNext()源码

    判断是否有下一个元素

    public boolean hasNext() {
        return cursor != size;
    }
    
    清单 3.Itr的next()源码

    获取集合下一个元素

    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];
    }
    
    清单 4.Itr的checkForComodification()源码

    作用modCount和expectedModCount不相等,抛出ConcurrentModificationException异常

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
    
    清单 5.ArrayList.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;
    }
    
    private void fastRemove(int index) {
        // modCount是AbstractList类中的一个成员变量
        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
    }
    
    清单 6.AbstractList类的modCount变量
    protected transient int modCount = 0;// AbstractList类的一个成员变量,对ArrayList执行add()和remove()操作,modCount值都会加1
    
    清单 7.Itr的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();
        }
    }
    
    清单 8.Itr的成员变量expectedModCount
    int expectedModCount = modCount;// Itr的成员变量,ArrayList修改次数的期望值,它的初始值为modCount
    

    分析:

    1.首先for in 语句是迭代器Iterator的简化版本

    证明:执行清单1并在清单2 hasNext()方法中打上断点,程序会在断点位置停下来。

    2.执行到Itr.next()时modCount和expectedModCount不一致

    执行for in 语句相应会执行清单3中Itr.next()方法,该方法中首先会调用checkForComodification()检查modCount和expectedModCount是否相等
    但是在执行ArrayList的remove()方法时只对modCount执行了加1操作,无法对ArrayList的内部类Itr的成员变量expectedModCount进行操作
    所以执行checkForComodification()才会报ConcurrentModificationException异常。因此不能在for in 循环中执行remove()方法。

    3.使用迭代器Itr的remove()方法可以保持modCount和expectedModCount一致

    迭代器Itr每执行一次remove()都会将modCount赋值给expectedModCount(清单7,第10行)

    结论:

    要在循环中对集合执行add()或remove()操作,要放到迭代器中,如清单8
    add()方法同理

    清单 9.Iterator中remove()
    List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add(null);
    ListIterator<String> iterator = list.listIterator();
    while (iterator.hasNext()) {
        String item = iterator.next();
        iterator.add("3");
        if ("2".equals(item)) {
            iterator.remove();
        }
    }
    

    相关文章

      网友评论

          本文标题:for in 循环中remove()抛出ConcurrentMo

          本文链接:https://www.haomeiwen.com/subject/tqavbktx.html