最近的工作中,遇到一个问题:对一个List进行遍历的时候将其中的元素删除掉,结果报java.util.ConcurrentModificationException,通过查看源码,得知原因了。
在ArrayList中的remove方法代码如下:
publicboolean remove(Object o) {
if (o ==null) {
for (int index =0; index < size; index++)
if (elementData[index] ==null) {
fastRemove(index);
returntrue;
}
}else {
for (int index =0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
returntrue;
}
}
returnfalse;
}
privatevoid fastRemove(int index) {
modCount++;//只增加了modCount
....
}
我们接着看看AbstractList
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
//AbstractCollection和List都继承了Collection
protected transient int modCount = 0;
private class Itr implements Iterator<E> { //内部类Itr
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification(); //特别注意这个方法
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch(IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet); //执行remove对象的操作
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount; //重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生
} catch(IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount) //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException
throw new ConcurrentModificationException();
}
}
}
所以,产生ConcurrentModificationException的原因就是:
执行remove(Object o)方法之后,modCount和expectedModCount不相等了。然后当代码执行到next()方法时,判断了checkForComodification(),发现两个数值不等,就抛出了该Exception。
解决的办法是:(列举其中一个解决办法)
System.out.println("-2-使用Iterator的remove");
list = test.buildList();
try {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
}
} catch (Exception e) {
// java.lang.IllegalStateException
e.printStackTrace();
}