Why can't I do:
Enumeration e = ...
for (Object o : e)
...
Why can't I do:
Enumeration e = ...
for (Object o : e)
...
Because Enumeration<T> doesn't extend Iterable<T>. Here is an example of making Iterable Enumerations.
As to why that's an interesting question. This isn't exactly your question but it sheds some light on it. From the Java Collections API Design FAQ:
Why doesn't Iterator extend Enumeration?
We view the method names for Enumeration as unfortunate. They're very long, and very frequently used. Given that we were adding a method and creating a whole new framework, we felt that it would be foolish not to take advantage of the opportunity to improve the names. Of course we could support the new and old names in Iterator, but it doesn't seem worthwhile.
That basically suggests to me that Sun wants to distance themselves from Enumeration, which is very early Java with quite a verbose syntax.
The new-style-for-loop ("foreach") works on arrays, and things that implement the Iterable interface.
It's also more analogous to Iterator than to Iterable, so it wouldn't make sense for Enumeration to work with foreach unless Iterator did too (and it doesn't).
Enumeration is also discouraged in favor of Iterator.
With java 8 and beyond this is possible:
import java.util.Collections;
import java.util.Enumeration;
Enumeration e = ...;
Collections.list(e).forEach(o -> {
... // use item "o"
});
Because an Enumeration (and most classes derived from this interface) does not implement Iterable.
You can try to write your own wrapper class.
We can use the for loop to iterate over an enumeration using the .values()
method which returns all the elements contained in the enumeration.
An example :
for (USERS_ROLES userRole: USERS_ROLES .values ()) {
System.out.println ("This is one user role:" + userRole.toString ());
}
I did it in java 10