LinkedList之modCount和expectedModCount
阿新 • • 發佈:2017-07-07
包括 expected 對象 one 拋出異常 pri blog 創建 就會
modCount和expectedModCount是用於表示修改次數的,其中modCount表示集合的修改次數,這其中包括了調用集合本身的add方法等修改方法時進行的修改和調用集合叠代器的修改方法進行的修改。而expectedModCount則是表示叠代器對集合進行修改的次數。
設置expectedModCount的目的就是要保證在使用叠代器期間,LinkedList對象的修改只能通過叠代器且只能這一個叠代器進行。
集合是如何保證的呢?
在創建叠代器的時候會把對象的modCount的值傳遞給叠代器的expectedModCount:
1 private class ListItr implementsListIterator<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 }
LinkedList之modCount和expectedModCount