Iterator用于遍历集合中的元素,适用于不知道集合内部结构的情况。用户不再与集合类交互,而是与Iterator交互,其清楚知道集合类的内部状态,通过控制iterator达到遍历集合的目的。
Iterator<E>接口:
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
如ArrayList中的私有类Itr实现Iterator<E>接口:
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();
}
}
//forEachRemaining方法此处略过
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
注意最后一个函数checkForComdification,检测ConcurrentModificationException异常。
反向输出也可以:
public interface ListIterator<E> extends Iterator<E>
ListIterator接口继承Iterator接口,实现从后往前遍历。(注意只有List集合有)