考试网 >> IT认证 >> JAVA >> JAVA指导 >> 深入浅出Java设计模式之迭代器模式

深入浅出Java设计模式之迭代器模式

发布时间:2006-06-28 11:09     点击:
分页:上一页  1 [2] 3  下一页

  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(IndexOutOfBoundsException e) {

  throw new ConcurrentModificationException();

  }

  }

  final void checkForComodification() {

  if (modCount != expectedModCount)

  throw new ConcurrentModificationException();

  }

  }

  至于迭代器模式的使用。正如引言中所列那样,客户程序要先得到具体容器角色,然后再通过具体容器角色得到具体迭代器角色。这样便可以使用具体迭代器角色来遍历容器了……

  四、 实现自己的迭代器

  在实现自己的迭代器的时候,一般要操作的容器有支持的接口才可以。而且我们还要注意以下问题:
分页:上一页  1 [2] 3  下一页
版权申明:未经书面授权请勿转载本站信息!!作品版权归所属媒体与作者所有!!
发表评论: 匿名发表 用户名: 查看评论
您将承担一切因您的行为、言论而直接或间接导致的民事或刑事法律责任
留言板管理人员有权保留或删除其管辖留言中的任意内容
本站提醒:不要进行人身攻击。谢谢配合。
在本站搜索相关信息
2003-2005 Ksw123.com All Rights Reserved. - TOP
Copyright © 2006 Ksw123.com. All rights reserved.中国考题网 版权所有