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();
}
}
主要是由于 cursor指针指向当前的位置的下一个元素,lastRet指向当前的位置;当删除完成后,cusor又回退了一位;lastRet又被重置了
本文深入解析了ArrayList中迭代器的工作机制,重点介绍了cursor和lastRet变量的作用:cursor指针指向当前位置的下一个元素,而lastRet则记录了当前位置。在删除操作后,cursor会回退一位,lastRet被重置,确保了迭代过程的一致性和安全性。
723

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



