Java Language Compare and Contains for Enum values


Example

Enums contains only constants and can be compared directly with ==. So, only reference check is needed, no need to use .equals method. Moreover, if .equals used incorrectly, may raise the NullPointerException while that's not the case with == check.

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!");
        }

    }
}

To group, complement, range the enum values we have EnumSet class which contains different methods.

  • EnumSet#range : To get subset of enum by range defined by two endpoints

  • EnumSet#of : Set of specific enums without any range. Multiple overloaded of methods are there.

  • EnumSet#complementOf : Set of enum which is complement of enum values provided in method parameter

    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");
          }
      }
    }