modCount和expectedModCount是用於表示修改次數的,其中modCount表示集合的修改次數,這其中包括了調用集合本身的add方法等修改方法時進行的修改和調用集合迭代器的修改方法進行的修改。而expectedModCount則是表示迭代器對集合進行修改的次數。
設置expectedModCount的目的就是要保證在使用迭代器期間,LinkedList對象的修改只能通過迭代器且只能這一個迭代器進行。
集合是如何保證的呢?
在創建迭代器的時候會把對象的modCount的值傳遞給迭代器的expectedModCount:
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的值不一致,從而產生異常:
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的值是否一致,不一致則拋出異常。
1 final void checkForComodification() { 2 if (modCount != expectedModCount) 3 throw new ConcurrentModificationException(); 4 }
