* 从功能上讲,在 Java 中一个迭代器应至少包含返回迭代器下一个元素的 next 方法和判断迭代器
是否还有下一个元素的 hasNext 方法
public interface Iterator<E> {
boolean hasNext(); // 还有没有下一个元素
E next(); // 下一个元素
default void remove() { // 移除当前元素,若未实现抛出 UnsupportedOperationException 异常
throw new UnsupportedOperationException("remove");
}
// 对剩余元素的操作,操作一次,消耗一个元素
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
// ArrayList 的 Iterator 仅支持单向遍历,通过游标和大小来判断是否还有下一个元素
// 当迭代器中没有元素时会向虚拟机抛出 NoSuchElementException,该异常会由虚拟机自动处理
// 使得迭代的行为可以停止
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
int expectedModCount = modCount;
// prevent creating a synthetic constructor
Itr() {}
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();
}
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}