ArrayList
的迭代器源码解析
要生成迭代武器,必须调用iterator
方法,并且iterator
方法在底层中调用了Iter
内部类
public Iterator<E> iterator() {
return new Itr();
}
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
//expectedModCount预计的次数 ,modCount修改的次数
int expectedModCount = modCount;
}
接下来介绍一下next
方法
public E next() {
//调用checkForComodification()方法
checkForComodification();
//把i赋予初值
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
//移动指针
cursor = i + 1;
//返回当前的值,让lastRet记录这个值的位置
return (E) elementData[lastRet = i];
}
//判断是否多线程修改了这个迭代器,可以使用迭代器,重写的方法来修改,就可以避免这种情况
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
接下来介绍一下remove
方法
public void remove() {
//还没有调用过next
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
//移除lastRet的位置的数据
ArrayList.this.remove(lastRet);
//让指针退回一格
cursor = lastRet;
//让lastRet重置,就不能够在调用remove方法了
lastRet = -1;
//这里让expectedModCount等于modCount,重新remove的方法的关键
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
接下来介绍一下hasNext
方法
public boolean hasNext() {
return cursor != size;
}