public abstract class AbstractList extends AbstractCollection implements List { …… //这个便是负责创建具体迭代器角色的工厂方法 public Iterator iterator() { return new Itr(); }
//作为内部类的具体迭代器角色
PRivate class Itr implements Iterator { int cursor = 0; int lastRet = -1; int eXPectedModCount = modCount;
public boolean hasNext() { return cursor != size(); }
public Object next() { checkForComodification(); try { Object next = get(cursor); lastRet = cursor++; return next; } catch(IndexOutOfBoundsException e) { checkForComodification(); throw new NoSUChElementException(); } }
public void remove() { if (lastRet == -1) throw new IllegalStateException(); checkForComodification();
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } 至于迭代器模式的使用。正如引言中所列那样,客户程序要先得到具体容器角色,然后再通过具体容器角色得到具体迭代器角色。这样便可以使用具体迭代器角色来遍历容器了……