java中模拟迭代器实现迭代数组

时间:2022-12-16 22:40:44
package interfacetest;

public class Sequence {
private Object[] items;
private int next = 0;

//初始化对象数组大小
private Sequence(int size) {
items = new Object[size];
}

//给数组添加元素
private void add(Object object) {
if (next < items.length) {
items[next++] = object;
}
}

//直接初始化一个数组
private Sequence(Object[] objects){
items = objects;
}


//迭代器的实现
public class SuquenceSelcetor implements Seletor {

private int i = 0;

@Override
public boolean hasNext() {
return i != items.length;
}

@Override
public Object next() {
return items[i++];
}

}

//获取一个迭代器
public Seletor seletor(){
return new SuquenceSelcetor();
}

public static void main(String[] args) {
//分别传入数组大小,和元素测试
Sequence sequence = new Sequence(10);
for (int i = 0; i < 10 ; i++) {
sequence.add(Integer.toString(i));
}
Seletor seletor = sequence.seletor();
while (seletor.hasNext())
System.out.println(seletor.next());


System.out.println("**********");
//直接传入一个数组测试
String [] strings = {"132","456","4578"};
Sequence sequence1 = new Sequence(strings);
Seletor seletor1 = sequence1.seletor();
while (seletor1.hasNext())
System.out.println(seletor1.next());
}

}

//迭代器接口
interface Seletor {
boolean hasNext();
Object next();
}