A for-loop to iterate over an enum in Java
To iterate over an enum
in Java using a for
loop, you can use the values()
method of the enum
type to get an array of all the enum values, and then use a standard for
loop to iterate over the array.
For example, consider the following enum
type:
public enum Color {
RED, GREEN, BLUE
}
To iterate over the Color
enum using a for
loop, you can use the following code:
for (Color c : Color.values()) {
System.out.println(c);
}
This will print all the enum values to the console:
RED
GREEN
BLUE
You can also use a traditional for
loop with an index variable to iterate over the enum values:
for (int i = 0; i < Color.values().length; i++) {
System.out.println(Color.values()[i]);
}
This will also print all the enum values to the console.
I hope this helps! Let me know if you have any questions.