LinkedList之modCount和expectedModCount

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         }
原文地址:https://www.cnblogs.com/zhangcaiwang/p/7131035.html