MaVVamaldo
MaVVamaldo

Reputation: 2535

iterating an enum with a while loop

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

Answers (2)

ptomli
ptomli

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

Related Questions