Iterating Over an Enum
Enhanced For Loops
An enhanced for loop can be used to iterate over a set of values.
for (<Variable Declaration> : <Set of Values>) {
//body
}
The keyword for
is followed by parenthesis and a variable declaration that is the same type as the values in the set. This is followed by a colon (:
), followed by the set of values that we will be iterating over.
Iterating Over an Enum
We can use the enhanced for loop to iterate over an enum
. The values that are iterated over are those that are the constants in the enum
.
Consider the following enum
example.
enum Directions {
NORTH, SOUTH, EAST, WEST
}
The values that we will iterate over are NORTH
, SOUTH
, EAST
, WEST
. The type of these constants are Directions
.
Accessing the Values of an enum
To access the values of an enum, we will need to use the values()
method. This method return the constants in the order that they are listed in the declaration.
Try this in the Java Playground.
- Run the code in the Java Playground to see what it does
- Create a
robotDirections
variable of type Directions
- Using the enhanced
for
loop, set robotDirections
to each value. Update the output to be the value of robotDirections
.
- Run the code. Your output should be the unchanged.
Resources