迭代器模式(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
迭代这个名词对于熟悉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
相关文章推荐
- 迭代器模式(Iterator Pattern)
- 迭代器模式【Iterator Pattern】
- Php设计模式之【迭代器模式Iterator Pattern】
- 设计模式:迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator Pattern)
- 设计模式之九:迭代器模式(Iterator Pattern)
- 第二十七章 迭代器模式(Iterator Pattern)
- 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator Pattern)部分代码
- 解读设计模式----迭代器模式(Iterator Pattern),谁才是迭代高手
- 迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator Pattern)
- Net设计模式实例之迭代器模式(Iterator Pattern)(2) 推荐
- 设计模式-迭代器模式(iterator pattern)
- 16.迭代器模式(Iterator Pattern)
- java设计模式---迭代器模式(iterator pattern)
- 【23种设计模式】之 迭代器模式(Iterator Pattern)
- .NET设计模式(18):迭代器模式(Iterator Pattern)
- 设计模式(C#)之迭代器模式(Iterator Pattern)