Iterating Over an Enum
An enhanced for loop can be used to iterate over a set of values, including enum values.
Basic Structure of an Enhanced for Loop
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.
for (<Data Type of the Set> <variable> : <Set of Values>) {
//body
}
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.
Basic Structure to Iterate 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.
for (<Enum Type> <variable> : <Enum Type>.values()) {
//body
}
Your Turn
Try this in the Java Playground.
- Predict the output of the following code.
- Run the code to determine if your prediction is correct.
- 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
Next Learn Tutorial