JDK7集合框架源码学习-ArrayList(2)迭代器

本文深入解析了Java中ArrayList内部迭代器的实现原理,包括其核心字段的作用及迭代过程中的并发修改检查机制,揭示了fail-fast行为背后的modCount计数器工作方式。
  1.     private class Itr implements Iterator<E> {
  2.         int cursor; // index of next element to return
  3.         int lastRet = -1; // index of last element returned; -1 if no such
  4.         int expectedModCount = modCount;

  5.         public boolean hasNext() {
  6.             return cursor != size;
  7.         }

  8.         @SuppressWarnings("unchecked")
  9.         public E next() {
  10.             checkForComodification();
  11.             int i = cursor;
  12.             if (i >= size)
  13.                 throw new NoSuchElementException();
  14.             Object[] elementData = ArrayList.this.elementData;
  15.             if (i >= elementData.length)
  16.                 throw new ConcurrentModificationException();
  17.             cursor = i + 1;
  18.             return (E) elementData[lastRet = i];
  19.         }

  20.         public void remove() {
  21.             if (lastRet < 0)
  22.                 throw new IllegalStateException();
  23.             checkForComodification();

  24.             try {
  25.                 ArrayList.this.remove(lastRet);
  26.                 cursor = lastRet;
  27.                 lastRet = -1;
  28.                 expectedModCount = modCount;
  29.             } catch (IndexOutOfBoundsException ex) {
  30.                 throw new ConcurrentModificationException();
  31.             }
  32.         }

  33.         final void checkForComodification() {
  34.             if (modCount != expectedModCount)
  35.                 throw new ConcurrentModificationException();
  36.         }
  37.     }

ArrayList 内部类.

modCount转自大飞博客:
需要注意的地方是AbstractList中的一个属性modCount。这个属性主要由集合的迭代器来使用,对于List来说,可以调用iterator()和listIterator()等方法来生成一个迭代器,这个迭代器在生成时会将List的modCount保存起来(迭代器实现为List的内部类),在迭代过程中会去检查当前list的modCount是否发生了变化(和自己保存的进行比较),如果发生变化,那么马上抛出java.util.ConcurrentModificationException异常,这种行为就是fail-fast.

其实modCount 就是modifyCount.作用类似于数据库的乐观锁版本列.

 int cursor;  初始化值为0.感觉这块不应该使用默认值.可读性差些。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29254281/viewspace-2121715/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29254281/viewspace-2121715/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值