Java Reference
In-Depth Information
Example 8.9.1-1. Iterating Over Enum Constants With An Enhanced
for
Loop
public class Test {
enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
}
}
This program produces the output:
WINTER
SPRING
SUMMER
FALL
Example 8.9.1-2. Use Of
java.util.EnumSet
For Subranges
import java.util.EnumSet;
public class Test {
enum Day { MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public static void main(String[] args) {
System.out.print("Weekdays: ");
for (Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY))
System.out.print(d + " ");
}
}
This program produces the output:
Weekdays: MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY
java.util.EnumSet
contains a rich family of static factories, so this technique can be gen-
eralized to work with non-contiguous subsets as well as subranges. At first glance, it
might appear wasteful to generate a
java.util.EnumSet
object for a single iteration, but
they are so cheap that this is the recommended idiom for iteration over a subrange.
Internally, a
java.util.EnumSet
is represented with a single
long
assuming the enum type
has 64 or fewer elements.