ArrayList的包里面的关于 Iterator 的实现源码:
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // 下一个元素的下标
int lastRet = -1; // 最后一个返回的下标,如果没有,返回 -1
int expectedModCount = modCount;
Itr() {}//默认的无参构造方法
public boolean hasNext() {
return cursor != size;//cursor 未到达线性表的末尾
}
@SuppressWarnings("unchecked")
public E next() {//获取 list 下一个元素
checkForComodification();//检查是否有并发的线程对list进行修改
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();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {//检查到并发线程的修改
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);//遍历线性表
}//在迭代的末尾更新一次,减少堆内存的写入压力
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {//检查是否有并发线程的修改,如果有就抛出异常
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}