I have a problem on a worksheet which is to create an adapter to convert an Enumeration to an Iterator. When I try to run the following code I get a null pointer exception.
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();
}
}
Another point to note is that I can not print out the int's from the Enumeration after I have created it in the first place.
Just use Collections. list(Enumeration<T> e) , which returns an ArrayList<T> . Then use ArrayList. iterator() to get an Iterator .
In the example of the micro-benchmark given, the reason the Enumeration is faster than Iterator is because it is tested first. ;) The longer answer is that the HotSpot compiler optimises a whole method when a loop has iterated 10,000 times.
Enumeration is like an Iterator , not an Iterable . A Collection is Iterable . An Iterator is not.
An enumeration (enum for short) in Java is a special data type which contains a set of predefined constants. You'll usually use an enum when dealing with values that aren't required to change, like days of the week, seasons of the year, colors, and so on.
No need to reinvent the wheel. Just use Collections.list(Enumeration<T> e)
, which returns an ArrayList<T>
. Then use ArrayList.iterator()
to get an Iterator
.
Enumerations now have a method to convert directly to an iterator:
enumeration.asIterator();
Wrong assignment in your constructor. It needs to be this.enmueration = enmueration;
enmueration
is the constructor argument, and this.enmueration
is the object attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With