Thursday 22 December 2016

A 'for' loop to iterate over an enum in Java



I have an enum in Java for the cardinal & 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?


Answer






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.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...