for-each或迭代器中调用List的remove方法会抛出ConcurrentModificationException的原因

简介: for-each循环遍历的实质是迭代器,使用迭代器的remove方法前必须调用一下next()方法,并且调用一次next()方法后是不允许多次调用remove方法的,为什么呢?接下来一起来看吧

for-each循环遍历的实质是迭代器,使用迭代器的remove方法前必须调用一下next()方法,并且调用一次next()方法后是不允许多次调用remove方法的,为什么呢?接下来一起来看吧


publicvoidremove(ArrayList<Integer>list) {
for (Integerinteger : list) {
if (integer==5) {
list.remove(integer);
            }
        }
    }

image.gif

比如这一段代码会抛出ConcurrentModificationException,为什么呢,请看源码


publicIterator<E>iterator() {
returnnewItr();
    }
/*** An optimized version of AbstractList.Itr*/privateclassItrimplementsIterator<E> {
intcursor;       // index of next element to returnintlastRet=-1; // index of last element returned; -1 if no suchintexpectedModCount=modCount;
publicbooleanhasNext() {
returncursor!=size;
        }
@SuppressWarnings("unchecked")
publicEnext() {
checkForComodification();
inti=cursor;
if (i>=size)
thrownewNoSuchElementException();
Object[] elementData=ArrayList.this.elementData;
if (i>=elementData.length)
thrownewConcurrentModificationException();
cursor=i+1;
return (E) elementData[lastRet=i];
        }
publicvoidremove() {
if (lastRet<0)
thrownewIllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor=lastRet;
lastRet=-1;
expectedModCount=modCount;
            } catch (IndexOutOfBoundsExceptionex) {
thrownewConcurrentModificationException();
            }
        }
@Override@SuppressWarnings("unchecked")
publicvoidforEachRemaining(Consumer<?superE>consumer) {
Objects.requireNonNull(consumer);
finalintsize=ArrayList.this.size;
inti=cursor;
if (i>=size) {
return;
            }
finalObject[] elementData=ArrayList.this.elementData;
if (i>=elementData.length) {
thrownewConcurrentModificationException();
            }
while (i!=size&&modCount==expectedModCount) {
consumer.accept((E) elementData[i++]);
            }
// update once at end of iteration to reduce heap write trafficcursor=i;
lastRet=i-1;
checkForComodification();
        }
finalvoidcheckForComodification() {
if (modCount!=expectedModCount)
thrownewConcurrentModificationException();
        }
    }

image.gif

实质是变化为迭代器实现,不管是迭代器里面的remove()还是next()方法,都会checkForComodification();而这个方法是判断modCount和expectedModCount是否相等,这个modCount是这个list集合修改的次数,每一次add或者remove都会增加这个变量


image.gif


然后迭代器每次去next或者去remove的时候检查checkForComodification();发现expectedModCount(这个迭代器修改的次数)和modCount(这个集合实际修改的次数)不相等,就会抛出ConcurrentModificationException


image.gif


迭代器里面没有add方法,用迭代器时,可以删除原来集合的元素,但是!一定要用迭代器的remove方法而不是集合自身的remove方法,否则抛异常。


再来看一个例子,这个是否正确?


publicvoidremove(ArrayList<Integer>list) {
Iterator<Integer>it=list.iterator();
while (it.hasNext()) {
it.remove();
    }
}

image.gif

这个第一次循环就会抛出IllegalStateException异常,为什么呢?那么我们再次看到迭代的remove方法


image.gif


关于lastRet,我们后面再讲,来看看,上一次remove()之后,lastRet变成了-1,然后没有it.next();继续执行remove(),首先判断if(lastRet<0)的时候就抛出了这个IllegalStateException异常。所以刚刚的代码是错的。

为什么要it.next()?难道next()方法又改了lastRet吗?它确确实实更改了。


image.gif


lastRet被赋值为i就不是-1了,下一次需要remove的时候就不会抛出IllegalStateException

那再来看看这个相同原理的例子


publicvoidremove(ArrayList<Integer>list) {
Iterator<Integer>it=list.iterator();
while (it.hasNext()) {
it.next();
it.remove();
it.remove();
    }
}

image.gif

这个正确吗?刚刚已经说了这个是错误的会抛出IllegalStateException异常,因为remove()调用一次后lastRet会变成-1,第二个remove()在第一句if(lastRet<0)的时候就异常了。


正确的使用:


publicvoidremove(ArrayList<Integer>list) {
Iterator<Integer>it=list.iterator();
while (it.hasNext()) {
it.next();
it.remove();
    }
}

image.gif

这里可不允许it.next()和it.remove()顺序交换!

因为lastRet的值初始化是-1,所以如果先remove()就会抛出IllegalStateException异常。


image.gif


综上

1.在for-each循环和迭代器中只可以做删除remove操作,不能做添加add操作。想要删除集合中的元素必须用迭代器的remove方法,不能添加操作add,因为add也会修改集合的modCount导致ConcurrentModificationException


2.用迭代器的remove()前必须调用一下next()方法,否则IllegalStateException


3.调用一次next()方法后是不允许多次调用remove方法,否则IllegalStateException


=========================Talk is cheap, show me the code========================

目录
相关文章
|
5天前
|
存储 Java
Java学习笔记 List集合的定义、集合的遍历、迭代器的使用
Java学习笔记 List集合的定义、集合的遍历、迭代器的使用
|
6天前
|
编译器
【Bug记录】list模拟实现const迭代器类
【Bug记录】list模拟实现const迭代器类
|
28天前
|
XML Java API
List与String相互转化的方法有哪些
摘要:本文概述了Java中List转换为String及反之的多种策略。使用`String.join()`可简洁地连接List元素;`StringBuilder`提供灵活控制;Java 8 Stream API收集器简化操作;Apache Commons Lang3的`StringUtils.join()`和Guava的`Joiner.on()`支持外部库的高效转换。
|
29天前
|
前端开发 Java 项目管理
List.of 问题之使用List.of方法为什么会引发前端解析失败的问题,如何解决
List.of 问题之使用List.of方法为什么会引发前端解析失败的问题,如何解决
|
1月前
|
存储 安全 Java
详解Java中集合的List接口实现的ArrayList方法 | Set接口实现的HashSet方法
详解Java中集合的List接口实现的ArrayList方法 | Set接口实现的HashSet方法
|
2月前
|
编译器 C语言 C++
C++ STL中list迭代器的实现
C++ STL中list迭代器的实现
C++ STL中list迭代器的实现
|
1月前
|
存储 缓存 安全
Java List操作详解及常用方法
Java List操作详解及常用方法
|
2月前
|
C++ 容器
【c++】优先级队列|反向迭代器(vector|list)
【c++】优先级队列|反向迭代器(vector|list)
14 0
|
2月前
|
Java
JAVA构建List集合为树形结构的方法和代码
JAVA构建List集合为树形结构的方法和代码
13 0
|
2月前
|
存储 缓存 编译器
【C++进阶】深入STL之list:模拟实现深入理解List与迭代器
【C++进阶】深入STL之list:模拟实现深入理解List与迭代器
19 0