定义:迭代器模式提供一种方法顺序访问一个聚合对象的各个元素,而又不暴露其内部的表示。
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
public interface Iterable<T> {
Iterator<T> iterator();
}
下面是AbstractList对Iterable实现
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { // List接口实现了Collection<E>, Iterable<E>
protected AbstractList() {
}
... //其它代码省略
public Iterator<E> iterator() {
return new Itr(); // 这里返回一个迭代器
}
private class Itr implements Iterator<E> { // 内部类Itr实现迭代器
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() { // 实现hasNext方法
return cursor != size();
}
public E next() { // 实现next方法
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() { // 实现remove方法
if (lastRet == -1)
throw new IllegalStateException();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}