您的位置:首页 > 其它

迭代器模式(Iterator Pattern)

2008-11-06 10:13 337 查看
一、 引言

迭代这个名词对于熟悉Java的人来说绝对不陌生。我们常常使用JDK提供的迭代接口进行java collection的遍历:

Iterator it = list.iterator();

//迭代器角色,仅仅定义了遍历接口

//容器角色,这里以List为例。它也仅仅是一个接口,就不罗列出来了

//具体容器角色,便是实现了List接口的ArrayList等类。为了突出重点这里指罗列和迭代器相关的内容

//具体迭代器角色,它是以内部类的形式出来的。AbstractList是为了将各个具体容器角色的公共部分提取出来而存在的。

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();

  try {

   AbstractList.this.remove(lastRet);

   if (lastRet < cursor)

    cursor--;

   lastRet = -1;

   expectedModCount = modCount;

  } catch
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: