patternjavaCritical
A for-loop to iterate over an enum in Java
Viewed 0 times
enumjavaoverforiterateloop
Problem
I have an
How can I write a
enum in Java for the cardinal and intermediate directions:public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}How can I write a
for loop that iterates through each of these enum values?Solution
.values()You can call the
values() method on your enum.for (Direction dir : Direction.values()) {
// do what you want
}This
values() method is implicitly declared by the compiler. So it is not listed on Enum doc.Code Snippets
for (Direction dir : Direction.values()) {
// do what you want
}Context
Stack Overflow Q#1104975, score: 1500
Revisions (0)
No revisions yet.