Compare and Contains for Enum values
suggest changeAn enum type contains only constants, and those constants can be compared directly with ==. Only a reference check is needed; there is no need to call equals. Calling equals on a null reference throws NullPointerException, which == does not.
enum Day {
GOOD, AVERAGE, WORST;
}
public class Test {
public static void main(String[] args) {
Day day = null;
if (day.equals(Day.GOOD)) {//NullPointerException!
System.out.println("Good Day!");
}
if (day == Day.GOOD) {//Always use == to compare enum
System.out.println("Good Day!");
}
}
}
EnumSet groups enum constants and can take a range or a complement:
EnumSet.range: the subset from one constant through another, in declaration order. The first argument must not come after the second.EnumSet.of: a set of specific constants, with no range. Several overloads exist.EnumSet.complementOf: the constants of the enum type that are not in the set passed in.
enum Page {
A1, A2, A3, A4, A5, A6, A7, A8, A9, A10
}
public class Test {
public static void main(String[] args) {
EnumSet<Page> range = EnumSet.range(Page.A1, Page.A5);
if (range.contains(Page.A4)) {
System.out.println("Range contains A4");
}
EnumSet<Page> of = EnumSet.of(Page.A1, Page.A5, Page.A3);
if (of.contains(Page.A1)) {
System.out.println("Of contains A1");
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents