在java语言中,ArrayList是一个很常用的类,在编程中经常要对ArrayList进行删除操作,在使用remove方法对ArrayList进行删除操作时,报java.util.ConcurrentModificationException异常,下面探讨一下该异常的原因以及解决办法。
原因:首先发现Java的for循环,就是将List对象遍历托管给Iterator,你如果要对list进行增删操作,都必须经过Iterator,否则Iterator遍历时会乱,所以直接对list进行删除时,Iterator会抛出ConcurrentModificationException异常
其实,每次foreach迭代的时候都有两部操作
第一步:iterator.hasNext() //判断是否有下个元素
public boolean hasNext() {
return cursor != size;
}
第二步:item = iterator.next() //下个元素是什么,并赋值给上面例子中的item变量
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];
}
通过debug调试,我们发现,checkForComodification时返回了异常,异常原因为 modCount != expectedModCount。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
进一步阅读源码,发现:
1.modCount 时List从new开始,被修改的次数。当List调用Remove等方法时,modCount++
2.expectedModCount是指Iterator现在期望这个list被修改的次数是多少次。是在Iterator初始化的时候将modCount 的值赋给了expectedModCount
那么就解释了为什么会报上述异常:
1.modCount 会随着调用List.remove方法而自动增减,而expectedModCount则不会变化,就导致modCount != expectedModCount。
2.在删除倒数第二个元素后,cursor=size-1,此时size=size-1,导致hasNext方法认为遍历结束。
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> listA=new ArrayList<>();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);
listA.add(5);
listA.add(6);
for(Integer a:listA){
System.out.println(a);
if (a==5) {
listA.remove(5);
}
}
}
}
上述代码加了打印后,输出1,2,3,4,5;进一步证明最后一个元素6并没有被遍历到。
解决方法:
在找到原因后,则进一步进行解决
经过查阅源码可以发现,iterator也有一个remove方法如下,其中有一个重要的操作为expectedModCount = modCount;这样就保证了两者的相等。
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 class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> listA=new ArrayList<>();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);
listA.add(5);
listA.add(6);
Iterator<Integer> it_b=listA.iterator();
while(it_b.hasNext()){
Integer a=it_b.next();
if (a==4) {
it_b.remove();
}
}
for(Integer b:listA){
System.out.println(b);
}
}
}