java.util.ConcurrentModificationException
转自http://www.blogjava.net/EvanLiu/archive/2008/08/31/224453.html
工作中碰到个ConcurrentModificationEx
ception。代码如下:
List list = ...;
for(Iterator iter = list.iterator(); iter.hasNext();) {
Object obj =iter.next();
...
if(***){
list.remove(obj);
}
}
在执行了remove方法之后,再去执行循环,iter.next()的时候,报java.util.ConcurrentModificationException(当然,如果remove的是最后一条,就不会再去执行next()操作了)
下面来看一下源码
public interfaceIterator<E> {
booleanhasNext();
Enext();
voidremove();
}
public interface Collection<E>extends Iterable<E> {
...
Iterator<E> iterator();
booleanadd(E o);
booleanremove(Object o);
...
}
这里有两个remove方法
接下来来看看AbstractList
public abstract classAbstractList<E> extendsAbstractCollection<E> implementsList<E> {
//AbstractCollection和List都继承了Collection
protectedtransient int modCount = 0;
privateclass 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 {