Java笔记20:迭代器模式
迭代器模式
所谓Iterator模式,即是Iterator为不同的容器提供一个统一的访问方式。本文以Java中的容器为例,模拟Iterator的原理。
1 定义一个容器Collection接口
public interface Collection {
void add(Object obj);
int size();
Iterator iterator();
}
2 定义一个Iterator迭代器的接口
public interface Iterator {
Object next();
boolean hasNext();
}
3 定义一个ArrayList,实现Collection接口,并写一个实现了Iterator接口的内部类
public class ArrayList implements Collection {
Object[] objects = new Object[10];
int index = 0;
public void add(Object obj) {
if(index == objects.length) {
Object[] newObjects = new Object[objects.length * 2];
System.arraycopy(objects, 0, newObjects, 0, objects.length);
objects = newObjects;
}
objects[index] = obj;
index ++;
}
public int size() {
return index;
}
public Iteratoriterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator {
private int currentIndex = 0;
@Override
public boolean hasNext() {
if(currentIndex >= index) {
return false;
} else {
return true;
}
}
@Override
public Objectnext() {
Object obj = objects[currentIndex];
currentIndex ++;
return obj;
}
}
}
4 编写测试程序类Test
public class Test {
public static void main(String[] args) {
Collection c = new ArrayList();
for(int i = 0; i < 5; i++) {
c.add("string " + i);
}
System.out.println(c.size());
Iterator it = c.iterator();
while(it.hasNext()) {
Object obj = it.next();
System.out.println(obj.toString() + " ");
}
}
}
运行结果:
5
string 0
string 1
string 2
string 3
string 4