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.
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.
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
robotDirectionsvariable of typeDirections - Using the enhanced
forloop, setrobotDirectionsto each value. Update the output to be the value ofrobotDirections. - Run the code. Your output should be the unchanged.
Resources
- Practice: Writing Expressions to Iterate over enum Values
- Learn: Introduction to enum Values
- Learn: enum Constructors and Methods