10_2, list foreach遍历删除 list.remove(obj)报错ConcurrentModificationException原因

**foreach删除元素报错java.util.ConcurrentModificationException**
 private static void removeList(){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }

        for (Integer string : list) {  //删除报错
            list.remove(string);
        }
    }

list修改会记录修改的次数, 在ArrayList和Itr内部内中都有记录
ArrayList modCount
Itr expectedModCount Itr是 ArrayList的内部类,实现了迭代器

每次修改modCout都会+1,调用迭代器的remove(),
第一步: ArrayList.this.remove(lastRet);会先去删除, modCount+1
第二步: 后面设置expectedModCount = modCount;

foreach遍历实际就是 调用Itr迭代器遍历,
Itr.next() 会调用checkForComodification()方法, 如果用list的remove(obj)方法, modCount被修改了
, 但是Itr迭代器中的expectedModCount没有变。 在Itr.next()中校验失败

 private class Itr implements Iterator<E> {
 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();
            }
        }
 public E next() {
            checkForComodification();
           	...
        }
final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

在这里插入图片描述

foreach循环删除报错,可查看: https://blog.csdn.net/m0_37372711/article/details/54613741

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章