Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use foreach on Java Enumeration?

Tags:

java

loops

Why can't I do:

Enumeration e = ... for (Object o : e)   ... 
like image 290
ripper234 Avatar asked Aug 06 '09 16:08

ripper234


People also ask

Can I iterate through enum Java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.

Can you iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.


1 Answers

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.

like image 78
cletus Avatar answered Oct 19 '22 17:10

cletus