-
private class Itr implements Iterator<E> {
-
int cursor; // index of next element to return
-
int lastRet = -1; // index of last element returned; -1 if no such
-
int expectedModCount = modCount;
-
-
public boolean hasNext() {
-
return cursor != size;
-
}
-
-
@SuppressWarnings("unchecked")
-
public E next() {
-
checkForComodification();
-
int i = cursor;
-
if (i >= size)
-
throw new NoSuchElementException();
-
Object[] elementData = ArrayList.this.elementData;
-
if (i >= elementData.length)
-
throw new ConcurrentModificationException();
-
cursor = i + 1;
-
return (E) elementData[lastRet = i];
-
}
-
-
public void remove() {
-
if (lastRet < 0)
-
throw new IllegalStateException();
-
checkForComodification();
-
-
try {
-
ArrayList.this.remove(lastRet);
-
cursor = lastRet;
-
lastRet = -1;
-
expectedModCount = modCount;
-
} catch (IndexOutOfBoundsException ex) {
-
throw new ConcurrentModificationException();
-
}
-
}
-
-
final void checkForComodification() {
-
if (modCount != expectedModCount)
-
throw new ConcurrentModificationException();
-
}
- }
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/
本文深入解析了Java中ArrayList内部迭代器的实现原理,包括其核心字段的作用及迭代过程中的并发修改检查机制,揭示了fail-fast行为背后的modCount计数器工作方式。

437

被折叠的 条评论
为什么被折叠?



