当使用iterator迭代器遍历集合时
List<Integer> integerList=new ArrayList<>();
Iterator<Integer> iterator = integerList.iterator();
while (iterator.hasNext()){
Integer integer=iterator.next();
integerList.remove(integer);
iterator.remove();
}
原因:
这里查看ArrayList实现iterator的源码,注意iterator的next()和remove()方法。
你会发现,iterator的hasnext()和remove()方法,都调用了checkForComodification(),当ArrayList的modCount (修改次数)!= expectedModCount(迭代器修改次数)时,会抛异常,当你调用iterator的remove()方法,会同步两个修改次数,而ArrayList不会同步,所以会抛异常
private class Itr implements Iterator<E> {
int cursor;
int lastRet = -1;
int expectedModCount = modCount;
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];
}
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();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}