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 theseenum
values?
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.
An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum , use the enum keyword (instead of class or interface), and separate the constants with a comma.
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With