In Java 5 and above you have the foreach loop, which works magically on anything that implements Iterable
:
for (Object o : list) {
doStuff(o);
}
However, Enumerable
still does not implement Iterable
, meaning that to iterate over an Enumeration
you must do the following:
for(; e.hasMoreElements() ;) {
doStuff(e.nextElement());
}
Does anyone know if there is a reason why Enumeration
still does not implement Iterable
?
Edit: As a clarification, I'm not talking about the language concept of an enum, I'm talking a Java-specific class in the Java API called 'Enumeration'.
Enumeration hasn't been modified to support Iterable because it's an interface not a concrete class (like Vector, which was modifed to support the Collections interface).
If Enumeration was changed to support Iterable it would break a bunch of people's code.
If you would just like it to be syntactically a little cleaner, you can use:
As an easy and clean way of using an Enumeration with the enhanced for loop, convert to an ArrayList with java.util.Collections.list.
(javax.swing.table.TableColumnModel.getColumns returns Enumeration.)
Note, this may be very slightly less efficient.
It doesn't make sense for
Enumeration
to implementIterable
.Iterable
is a factory method forIterator
.Enumeration
is analogous toIterator
, and only maintains state for a single enumeration.So, be careful trying to wrap an
Enumeration
as anIterable
. If someone passes me anIterable
, I will assume that I can calliterator()
on it repeatedly, creating as manyIterator
instances as I want, and iterating independently on each. A wrappedEnumeration
will not fulfill this contract; don't let your wrappedEnumeration
escape from your own code. (As an aside, I noticed that Java 7'sDirectoryStream
violates expectations in just this way, and shouldn't be allowed to "escape" either.)Enumeration
is like anIterator
, not anIterable
. ACollection
isIterable
. AnIterator
is not.You can't do this:
So it wouldn't make sense to do this:
There is no
Enumerable
equivalent toIterable
. It could be added without breaking anything to work in for loops, but what would be the point? If you are able to implement this newEnumerable
interface, why not just implementIterable
instead?AFAIK Enumeration is kinda "deprecated":
I hope they'll change the Servlet API with JSR 315 to use Iterator instead of Enumeration.