javaenum-map

Use enum that implements interface as parameter as key in EnumMap


I want to have a family of child classes that extend BaseClass, which has in turn a EnumMap defined. Depending on the IDE I plug this code in. It tells me that the Constructor

EnumMap<B, Integer>()

is not defined, respectively B is not within the specified bounds.

interface A {}
enum B implements A {hello, world}

abstract class BaseClass {
    protected EnumMap<? extends A, Integer> baseMap;
}

class ChildClass extends BaseClass {
    public ChildClass () {
        baseMap = new EnumMap<B,Integer>();
    }
}

E.g. the third last line gives me troubles. I don't see what is wrong.


Solution

  • EnumMap takes the enum in the constructor:

    baseMap = new EnumMap<B,Integer>(B.class);
    

    And as we're in a post Java 7 world

    baseMap = new EnumMap<>(B.class);
    

    I would suggest using a Map in the declaration - program to the interface:

    protected Map<? extends A, Integer> baseMap;