Reputation: 2535
Sorry for the very noob question. Let's suppose I have an enum like so
public enum MyElementType {
TYPE_ONE,
TYPE_TWO,
TYPE_THREE;
}
When I want to loop over this enum, I always see this solution:
for(MyElementType type: MyElementType.values())
{
//do things
}
I wonder if there exist a viable solution with the while loop. Seraching around I see that Enumeration interface exposes the method hasMoreElements() but I don't know how to link the things together. Any advice?
Upvotes: 0
Views: 4041
Reputation: 11818
Why do you want to use a while loop rather than the for-each you more typically see?
In any case, it's pretty simple
Set<MyElementType> elements = EnumSet.allOf(MyElementType.class);
Iterator<MyElementType> it = elements.iterator();
while (it.hasNext()) {
MyElementType el = it.next();
// etc
}
// or
Iterator<MyElementType> it = Arrays.asList(MyElementType.values()).iterator();
Upvotes: 3
Reputation: 19225
Take a look @ http://www.javaspecialists.eu/archive/Issue107.html
Upvotes: 1