记得以前使用过一个由apache项目组提供的array遍历器,觉得挺通用,也挺方便的。近日在自己的项目用到了vector的遍历,所以就想也用一个vector的iterator.所以就自己写了一个,其实也很简单的。
对于vector,如果我们不用遍历,那么就要自己去写循环,也是从实现结果上来说是一样的。可能的实现如下:
vector v= 一个vector的实例。
for(int i=0;i
object obj=v.get(i);
}
我们知道,如果自己想要实现遍历,只要实现iterator接口,然后重载其三个方法就可以了。我的代码如下:
package org.zy.common.util;
import java.util.iterator;
import java.util.vector;
public class vectoriterator implements iterator{
private vector v;
private int currentindex=0;
public vectoriterator(){
}
public vectoriterator(vector v){
this.v=v;
}
public boolean hasnext() {
if(this.currentindex
return true;
}else{
system.out.println("out of the bound ");
}
return false;
}
public object next() {
return this.v.get(this.currentindex++);
}
public void remove() {
this.v.remove(this.currentindex);
}
public static void main(string[] args){
vector v=new vector();
v.add(new string("aaa"));
v.add(new string("bbb"));
v.add(new string("ccc"));
//system.out.println(v);
iterator iter=new vectoriterator(v);
while(iter.hasnext()){
string str=(string)iter.next();
system.out.println(str);
}
}
}
上面的三个方法是我们需要自己重载的方法,main方法的部分是我们调用的过程。
以后我们在使用的时候,只需要把这个类导入我们的工程,或者打成jar的包导入工程,就可以使用了。
同样的道理,我们也可以自己去写一个数组iterator的实现类来实现数组的遍历。
学会使用遍历器,可以为我们的使用带来很大的方便。
闽公网安备 35060202000074号