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

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


.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.


All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type:

 for (Direction d : Direction.values()) {     System.out.println(d); }


You can do this as follows:

for (Direction direction : EnumSet.allOf(Direction.class)) {  // do stuff}