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 }