Java Reference
In-Depth Information
LOW
LOW
true
The reverse lookup for enum constants is case-sensitive. If you use an invalid constant name with the
valueOf() method, an IllegalArgumentException is thrown. For example, Severity.valueOf("low") will throw an
IllegalArgumentException stating that no enum constant “low” exists in the Severity enum.
Range of Enum Constants
The Java API provides a java.util.EnumSet collection class to work with ranges of enum constants of an enum type.
The implementation of the EnumSet class is very efficient. Suppose you have an enum type called Day as shown in
Listing 18-11.
Listing 18-11. A Day Enum Type
// Day.java
package com.jdojo.enums;
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
You can work with a range of days using the EnumSet class, for example, you can get all days between MONDAY and
FRIDAY . An EnumSet can contain enum constants only from one enum type. Listing 18-12 demonstrates how to use the
EnumSet class to work with the range for enum constants.
Listing 18-12. A Test Class to Demonstrate How to Use the EnumSet Class
// EnumSetTest.java
package com.jdojo.enums;
import java.util.EnumSet;
public class EnumSetTest {
public static void main(String[] args) {
// Get all constants of the Day enum
EnumSet<Day> allDays = EnumSet.allOf(Day.class);
print(allDays, "All days: " );
// Get all constants from MONDAY to FRIDAY of the Day enum
EnumSet<Day> weekDays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
print(weekDays, "Weekdays: ");
// Get all constants that are not from MONDAY to FRIDAY of the
// Day enum Essentially, we will get days representing weekends
EnumSet<Day> weekends = EnumSet.complementOf(weekDays);
print(weekends, "Weekends: ");
}
 
Search WWH ::




Custom Search