ArrayList在循环遍历的过程中,使用remove删除对象,会造成java.util.ConcurrentModificationException异常
public static void main(String[] args){ArrayList<Integer> list = new ArrayList();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);for(Integer data : list){System.out.print
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
for(Integer data : list){
System.out.println("===="+data);
if(data == 5){
list.remove(data);
}
}
}
输出结果
====1
====2
====3
====4
====5
具体分析下:ArrayList继承AbstractList,在抽象类AbstractList里有定义了modcount变量,用来记录数组变量被修改的次数
protected transient int modCount = 0;
在add、remove等方法里,都会对modCount进行加1运算。

另外还定义了expectedModCount,初始值等于modCount,modCount在ArrayList初始化的时候,每new一次,都会加1,所以初始值等于size()
/** * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. * 迭代器认为backingList应该具有的modCount值。如果违反了这个期望,迭代器就会检测到并发修改 */ int expectedModCount = modCount;
modCount会随着remove方法减少,而expectedModCount不变,导致两者不相等,进而抛出异常。
为什么上面的demo,删除data=5,不会报错呢?
AbstractArrayList有定义游标cursor,初始值=0,当for循环或者iterator进入下一个循环时,cursor自动加1。
直到cursor == list.size,hasNext() 返回false,结束循环。
/** * Index of element to be returned by subsequent call to next. */ int cursor = 0;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
所以,当删除完data=5之后,下一个循环判断,list.size = 5,cursor=5,结束循环,不会报错。
另外一种其他,比如删除data=3,modCount=6,当data=3的时候,modCount++,等于7,而expectedModCount 没有重新赋值,
导致expectedModCount != modCount,抛出异常。来看下源码
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
for(Integer data : list){
System.out.println("===="+data);
if(data == 3){
list.remove(data);
}
}
}
=========================================================
====1
====2
====3
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at com.ylzinfo.hrmanage.system.service.impl.Test.main(Test.java:76)


解决方案
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
ArrayList<Integer> removeList = new ArrayList<>();
removeList.add(3);
list.removeAll(removeList);
for(Integer data : list){
System.out.println("===="+data);
/*if(data == 3){
list.remove(data);
}*/
}
}
创建一个数组来存储要删除的对象,使用removeAll()的方法,来删除对象,这样就正常了。
更多推荐




所有评论(0)