对list进行add或delete时不能使用foreach循环原因
错误写法
//对list进行add或delete时不能使用foreach循环时会报java.util.ConcurrentModificationException
//错误写法
@Test
public void testList() {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
//Iterator<String> ite = list.iterator();
//使用foreach循环时会报java.util.ConcurrentModificationException
for (String str : list) {
if("3".equals(str)) {
list.remove(str);
}
}
}
正确写法
//正确写法1:使用Iterator迭代器,删除用ite.remove()
@Test
public void testList2() {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
Iterator<String> ite = list.iterator();
//使用foreach循环时会报java.util.ConcurrentModificationException
while(ite.hasNext()) {
String str = ite.next();
if("3".equals(str)) {
ite.remove();
}
}
}
//正确写法2:使用普通for循环
@Test
public void testList3() {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
if("3".equals(str)) {
list.remove(str);
}
}
}
原因
第一种使用增强for循环,实际上会调用list.iterator()方法进行迭代。那为什么使用iterator就报错呢?我们需要跟下源码,源码如下:
一:java.util.ArrayList.iterator()源码:
public Iterator<E> iterator() {
return new Itr();
}
二:点进new Itr()方法:
这是在ArrayList类里的私有类,先整体看下,再逐步分析。
/**
* An optimized version of AbstractList.Itr
*/
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;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
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];
}
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();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
其中有一行代码:
modCount在ArrayList中标识当前对象的修改次数,在进行ArrayList中add、remove方法中都对modCount进行了修改:
add方法也有修改,在这就不贴图了,可以看下源码。
我们继续往下看java.util.ArrayList.Itr.hasNext()方法,这里没有抛异常,可以先不用看
然后看java.util.ArrayList.Itr.next()方法
点进checkForComodification方法,异常就是这里抛出的:
在创建Itr对象时就将ArrayList的修改次数modCount赋值给Itr迭代器对象,如果在迭代期间ArrayList对象被操作(remove和add)了导致modCount 值修改,就会报异常ConcurrentModificationException。
我们前面提到的错误写法中,报错原因是和以下因素有关:
cursor:下一个元素的索引
size:集合长度
modCount:集合被修改的次数
expectedModCount:期望被修改的次数(我也不知道这个怎么翻译),在创建Itr对象时,modCount的值赋给了expectedModCount
我们再来看下例子:
具体流程
这里进行了3次add,所以size=3,modCount=3,expectedModCount=3,
当进行第一次ite.hasNext()时,cursor=0,此时cursor!=size为true,进入ite.next()方法:next()方法调用checkForComodification(),此时modCount != expectedModCount为false,不抛异常;进入第二次循环,调用ite.hasNext(),cursor=1,size=3,modCount=3,expectedModCount=3,不抛异常,然后进入第三次循环,调用ite.hasNext(),cursor=2,size=3,modCount=3,expectedModCount=3,不抛异常,但是
“3”.equals(str)为true,list进行删除操作;进入第四次循环,此时cursor=3,size=2,modCount=4,expectedModCount=3,cursor!=size为true,又继续调用next方法,此时modCount != expectedModCount为true,所以抛出异常。所以是在第四次循环时抛出的错误信息。
文字描述太繁琐,可以参考下表格:
为什么删除2的时候不报错
因为第二次循环的时候,“2”.equals(str)为true,经过remove,size变为2,等第三次循环的时候cursor!=size为false,跳出了循环,所以不报错。同理如果测试类中,list只add两次,删除1不会报错,删除2就会报错。