迭代模式:提供一种顺序访问存储结构过程的模式。
实现过程:一个接口类:Iterator,提供hasNext()和next()方法接口;
提供一个实现Iterator接口的迭代子类;
需实现顺序访问的类,提供一个生成迭代子类的方法Iterator(),在这个方法里面创建一个对应的迭代子类并将数据传递过去。
代码:
public interface Iterator<E> {
public boolean hasNext();
public E Next();
}
public class WshArrayList {
Object[] o=new Object[15];
int i=0;
public Iteration iteration(){
return new WshArrayListIteration(o);
}
public boolean add(Object a){
if(i<o.length){
o[i++]=a;
return true;
}
return false;
}
}
public class WshArrayListIteration implements Iteration {
Object[] o=null;
int i=0;
WshArrayListIteration(Object[] o){
this.o=o;
}
public boolean hasNext() {
if(o!=null&&i<o.length-1&&o[i]!=null){
return true;
}
return false;
}
public Object Next() {
if(o!=null&&i<o.length-1){
return o[i++];
}
return null;
}
}
本文介绍了一种用于顺序访问存储结构的过程——迭代模式。通过定义Iterator接口并实现特定的迭代子类,使得可以统一地遍历不同的集合对象。文章还提供了一个具体的实现示例,包括WshArrayList类及其迭代器。
530

被折叠的 条评论
为什么被折叠?



