本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前2天在csdn论坛上看到一个问题,就是使用for-each时,删除数据报错的一个问题;仔细debug看源码之后把问题搞清楚了,问题不难写一篇文章记录一下;
问题代码:
List<Integer> list = new ArrayList<>();
for (int i = 0; i <10 ; i++) {
list.add(i);
}
for (Integer integer : list) {
list.remove(integer);
}
报错信息:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at filter.TE.main(TE.java:19)
在for-each中循环删除数据会报错;那报错的原因是什么呢?我们在报错行中可以看到和ArrayList的内部类Itr有关系。因此我们重点关注Iter类;Iter源码;
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;//modCount是list修改次数;
Itr() {}
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];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
//没有用到的方法就不贴出来了
}
使用for-each循环时,首先会调用iterator()方法,创建一个Iter对象;然后由Iter对象负责遍历数组;在初始化Iter对象时,有个比较关键的属性: expectedModCount ;初始化:expectedModCount = modCount; 这个值是for-each循环时删除报错的原因;
for-each循环执行流程:
modCount:ArrayList的一个属性值,ArrayList的add,remove操作都会改变modCount的值;因此将add,remove操作放到for-each循环体中,导致modCount值改变,在下一次循环时检查到expectedModCount 与 modCount的值不相等就会导致报错;