具体来说就是,当创建了iterator后,如果对list进行了结构性的修改,并且不是通过iterator的方法进行的修改(add、remove)那么就会抛出@ConcurrentModificationException异常
LinkedList中,定义了私有类ListItr实现ListIterator接口,在该类中定义了一个名叫expectedModCount的int变量,且=modCount
该值的作用就是控制在使用Iterator进行集合操作时,保证并发访问的安全型,如果在调用iterator的方法操作集合时,发现expectedModcount != modCount,则会抛出@ConcurrentModificationException异常
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
......
}
比如说ListItr中的remove方法
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
//unlink方法会使modCount+1
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
//期望的修改次数+1
expectedModCount++;
}
//检查两者是否相等
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
但如果在使用iterator进行操作时,直接调用了非iterator的修改方法,那么modCount和expectModCount就不相等,抛出异常