Use Java 5 for with an Enumeration

Reading the post Searching Jars Redux on the "Code To Joy" blog, where Michael shows a closure Example in Java iterating through Jar content, saying " old-style Enumeration, don't blame me or closures!" about some ugly code using an Enumeration. It would be nice to just use for to iterate over an enumeration. This can be done easily. You can use Enumerations with the Java 5 for syntax when using a little Adapter around an Enumeration.

  public static void main(String[] args) {
    Vector<String> vector = new Vector<String>();
    vector.add("Stephan");
    for (String name : iterate(vector.elements())) {
      System.out.println("Name: " + name);
    }
  }

  public static <T> Iterable<T> iterate(Enumeration<T> enumeration) {
    return new IterableEnumeration<T>(enumeration);
  }

The IterableEnumeration is quite easy to write:

public class IterableEnumeration<T> implements Iterable<T>, Iterator<T> {
    private Enumeration<T> enumeration;

    public IterableEnumeration(Enumeration<T> enumeration) {
      this.enumeration = enumeration;
    }

    public Iterator<T> iterator() {
      return this;
    }

    public boolean hasNext() {
      return enumeration.hasMoreElements();
    }

    public T next() {
      return enumeration.nextElement();
    }

    public void remove() {
      throw new UnsupportedOperationException();
    }
  }

Together with static imports and a static iterate method, the Java code looks much nicer.

Go for more beautiful Java.

Thanks for listening.