Use Java 5 for with an Enumeration
Published November 3rd, 2007 in Beautiful Java, JavaReading 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.
10 Responses to “Use Java 5 for with an Enumeration”
- 1 Pingback on Nov 26th, 2007 at 12:36 am
Stephan,
Nice job! I hadn’t considered a way to bring Enumeration into Java 5
Michael E.
Thanks
-stephan
Another example:
http://binkley.blogspot.com/2004/08/supporting-old-code.html
Ah yes, as I said it’s easy to do. Would be nice if Java supported Adapter/Delegation classes with some nice syntactic sugar.
At least static imports shorten the code to use the Adapter.
Incredibly simple and useful!
Thanks a lot!
What is wrong with Collections.list() it’s been around since jdk 1.4
ArrayList list(Enumeration e)
Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
http://supercsv.sourceforge.net/
I guess Collections.list() returns a new List not a wrapper around the Enumeration. So this will create a new object and a.) the Enumeration is iterated (which might be expensiv, think of 1 billion entries, while you only want the first 10) b.) memory for the entries is created (think of 1 billioen entries again, while you only want the first 10).
See some enhancement at http://tavi-mytechblog.blogspot.com/… eventually let me know what you think…
Thanks
Sorry, the address is: http://tavi-mytechblog.blogspot.com/