我在工作表上有一个问题,即创建一个适配器以将枚举转换为迭代器。当我尝试运行以下代码时,我得到一个空指针异常。
import java.util.Vector;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
public class ConvertEnumeration {
public static void main(String [] args) {
int [] ourArray = {0,1,2,3,4,5,6,7,8,9};
Vector vector = new Vector(Arrays.asList(ourArray));
//Get Enumerator
Enumeration enumerator = vector.elements();
EnumerationToIterator enumToIt = new EnumerationToIterator(enumerator);
while(enumToIt.hasNext()) {
System.out.println(enumToIt.next());
}
}
}
//Convert our enumeration to Iterator!
class EnumerationToIterator implements Iterator {
//Our enumeration
Enumeration enmueration;
//Constructor
public EnumerationToIterator(Enumeration enmueration){
enmueration = this.enmueration;
}
//Our Methods
public boolean hasNext(){
return enmueration.hasMoreElements();
}
public Object next(){
return enmueration.nextElement();
}
public void remove(){
throw new UnsupportedOperationException();
}
}
需要注意的另一点是,在我首先创建枚举之后,我无法从枚举中打印出 int。