Handle Enumeration <T> as Iterator <T>
I have a class that implements the Enumeration<T> interface, but the Java foreach loop requires an Iterator<T> interface. Is there an Enumeration to Iterator adapter in the standard Java library?
You need the so-called βAdapterβ to adapt Enumeration to an Iterator incompatible with other parameters. Apache collection collections have an EnumerationIterator . Using:
Iterator iterator = new EnumerationIterator(enumeration); If you just want something to be repeated in a for-each loop (so that Iterable and not only Iterator), always java.util.Collections.list(Enumeration<T> e) (without using any external libraries).
a) I'm sure you mean Enumeration , not Enumerator
b) Guava provides the Helper method Iterators.forEnumeration(enumeration) which generates an iterator from Enumeration, but that will not help you either, since you need Iterable (the iterator provider), not Iterator
c) you can do this with this helper class:
public class WrappingIterable<E> implements Iterable<E>{ private Iterator<E> iterator; public WrappingIterable(Iterator<E> iterator){ this.iterator = iterator; } @Override public Iterator<E> iterator(){ return iterator; } } And now your client code will look like this:
for(String string : new WrappingIterable<String>( Iterators.forEnumeration(myEnumeration))){ // your code here } But is it worth the effort?
No need to collapse by yourself. Check out the Google Guava library. Specifically
Iterators.forEnumeration() There is nothing that is part of the standard library. Unfortunately, you will have to flip your own adapter. There are examples of what others have done, for example:
or in collections of EnumerationUtils collections
import static org.apache.commons.collections.EnumerationUtils.toList
toList(myEnumeration) If you can change the class, you can simply implement Iterator<T> and add the remove method.