首页 > 其他 > 详细

LinkedList之modCount和expectedModCount

时间:2017-07-07 11:31:05      阅读:340      评论:0      收藏:0      [点我收藏+]

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         }

 

LinkedList之modCount和expectedModCount

原文:http://www.cnblogs.com/zhangcaiwang/p/7131035.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!