我在工作表上遇到问题,即创建一个将Enumeration转换为Iterator的适配器。当我尝试运行以下代码时,我得到一个空指针异常。
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。
答案 0 :(得分:37)
无需重新发明轮子。只需使用Collections.list(Enumeration<T> e)
即可返回ArrayList<T>
。然后使用ArrayList.iterator()
获取Iterator
。
枚举现在have a method直接转换为迭代器:
enumeration.asIterator();
答案 1 :(得分:8)
Java 9提供了一种新的默认方法:Iterator<E> asIterator()
答案 2 :(得分:5)
构造函数中的错误赋值。它必须是this.enmueration = enmueration;
enmueration
是构造函数参数,this.enmueration
是对象属性。
答案 3 :(得分:4)
public class ConvertEnumeration {
public static void main(String [] args) {
// int [] ourArray = {0,1,2,3,4,5,6,7,8,9};
Vector<Integer> vector = new Vector<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9));
//Get Enumerator
Enumeration<Integer> enumerator = vector.elements();
EnumerationToIterator<Integer> enumToIt = new EnumerationToIterator<Integer>(enumerator);
while(enumToIt.hasNext()) {
System.out.println(enumToIt.next());
}
}
}
//Convert our enumeration to Iterator!
class EnumerationToIterator<T> implements Iterator<T> {
//Our enumeration
Enumeration<T> enmueration;
//Constructor
public EnumerationToIterator(Enumeration<T> enmueration){
this.enmueration = enmueration;
}
//Our Methods
public boolean hasNext(){
return enmueration.hasMoreElements();
}
public T next(){
return enmueration.nextElement();
}
public void remove(){
throw new UnsupportedOperationException();
}
}