Search code examples
javaenumsenum-map

Unable to construct EnumMap inside the initializer of the enum being mapped


In my code, I have an enum in which each value stores a separate EnumMap. However, when I try to initialize the EnumMap in a constructor or initializer, using the following code:

public static void main(String[] args) {
   RPS.values(); // forces initialization of enum values
}

enum RPS {
   ROCK,
   PAPER,
   SCISSORS;
   EnumMap<RPS,Boolean> matchups;
   {
      matchups = new EnumMap<>(RPS.class);
   }
}

it throws an ExceptionInInitializerError caused by a NullPointerException. However, no error is thrown when I initialize it outside of the constructor, like in the following code:

public static void main(String[] args) {
   for (RPS val:RPS.values())
      val.matchups = new EnumMap<>(RPS.class);
}

enum RPS {
   ROCK,
   PAPER,
   SCISSORS;
   EnumMap<RPS,Boolean> matchups;
}

Why does this error occur and how can I fix it?


Solution

  • Just move your initialisation to a static block, as RPS enum values are determined by then:

    enum RPS {
       ROCK,
       PAPER,
       SCISSORS;
    
       EnumMap<RPS,Boolean> matchups;
       static
       {
            for (RPS val:RPS.values())
                val.matchups = new EnumMap<>(RPS.class);
       }
    }