modCount和expectedModCount是用于表示修改次数的,其中modCount表示集合的修改次数,这其中包括了调用集合自己的add方法等修改方法时进行的修改和调用集合迭代器的修改方法进行的修改。而expectedModCount则是表示迭代器对集合进行修改的次数。spa
设置expectedModCount的目的就是要保证在使用迭代器期间,LinkedList对象的修改只能经过迭代器且只能这一个迭代器进行。code
集合是如何保证的呢?对象
在建立迭代器的时候会把对象的modCount的值传递给迭代器的expectedModCount:blog
1 private class ListItr implements ListIterator<E> { 2 private Node<E> lastReturned; 3 private Node<E> next; 4 private int nextIndex; 5 private int expectedModCount = modCount;
若是建立多个迭代器对一个集合对象进行修改的话,那么就会有一个modCount和多个expectedModCount,且modCount的值之间也会不同,这就致使了moCount和expectedModCount的值不一致,从而产生异常:it
1 public E next() { 2 checkForComodification(); 3 if (!hasNext()) 4 throw new NoSuchElementException(); 5 6 lastReturned = next; 7 next = next.next; 8 nextIndex++; 9 return lastReturned.item; 10 }
上面的代码中的checkForComodification会检查modCount和expectedModCount的值是否一致,不一致则抛出异常。io
1 final void checkForComodification() { 2 if (modCount != expectedModCount) 3 throw new ConcurrentModificationException(); 4 }