How do you retrieve all constants of an enum type, and how would you iterate over them?
Short answer
Every enum implicitly has a static values() method (generated automatically by the compiler) returning an array containing all the enum's constants in their declared order, which can be iterated directly with a for-each loop -- useful for populating a dropdown of options…
Advertisement
AModel answer
Every enum implicitly has a static values() method (generated automatically by the compiler) returning an array containing all the enum's constants in their declared order, which can be iterated directly with a for-each loop -- useful for populating a dropdown of options, validating input against all possible values, or any scenario needing to process every constant generically without hardcoding each one individually.
enum Season { SPRING, SUMMER, FALL, WINTER }
for (Season season : Season.values()) {
System.out.println(season);
}
// Prints: SPRING, SUMMER, FALL, WINTER, in declaration orderReal-world example
A settings UI populating a dropdown list of available themes iterates over ThemeOption.values() to generate the list of choices dynamically, automatically staying in sync if a new theme constant is added later without needing to update the UI population code itself.
Likely follow-ups
- Does calling values() repeatedly return the same array instance or a new copy each time, and why does that matter?
- How would you convert the values() array into a List or Stream for further processing?
Related topics