下图是迭代器的源码,对应都有注释
主要关注hasNext、next、remove这三个方法
其中next2方法是对next的方法改造,功能一致
同理,remove2方法是对remove的方法改造,功能一致
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;
Itr() {}
//咱们创建迭代器实例后,cursor默认为0
//首先第一步如果ArrayList中有元素,那么该方法则返回true
public boolean hasNext() {
return cursor != size;
}
//接下来看next方法,抛异常的暂时不管
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
//步骤一:先把cursor赋值给i
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
//获取到ArrayList底层的数组
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
//步骤二:让cursor又等于i+1,实际咱们刚刚令i=cursor
cursor = i + 1;
//这个时候先把i赋值给lastRet,再获取的元素elementData[i]
//这个i实际上是刚进入方法的步骤一
return (E) elementData[lastRet = i];
}
public E next2() {
Object[] elementData = ArrayList.this.elementData;
return (E) elementData[lastRet = cursor++];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
//移除元素是调用ArrayList的remove方法
//底层是通过index来移除,例:移除index=3(注:index是从0开始),则把index从4到最后重新拷贝到index=3的位置
ArrayList.this.remove(lastRet);
//在hasNext方法中lastRet是等于i的,cursor是比i大1
//在这一步,相当于让cursor-1
cursor = lastRet;
//把lastRet重置为-1,可以防止重复调用2次remove
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void remove2() {
try {
ArrayList.this.remove(lastRet);
cursor--;
lastRet = -1;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
欢迎各位同学一起交流,有不对的地方欢迎指出