Search code examples
javaiteratorforeachenumerationadapter

Treat Enumeration<T> as Iterator<T>


I have a class that implements the Enumeration<T> interface, but Java's foreach loop requires the Iterator<T> interface. Is there an Enumeration to Iterator Adapter in Java's standard library?


Solution

  • You need a so called "Adapter", to adapt the Enumeration to the otherwise incompatible Iterator. Apache commons-collections has EnumerationIterator. The usage is:

    Iterator iterator = new EnumerationIterator(enumeration);