Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Enum with generic type Enum

Tags:

java

I have the following interface and class definition.

interface A
{
}

class B
{
    public static enum C implements A
    {
        c1, c2, c3;
    }

    public static enum D implements A
    {
        d1, d2, d3;
    }

    public static enum E implements A
    {
        e1, e2, e3;
    }
}

Now I have a class where I declare a Map and assign the enum as key and set a value.

class Test
{
    private Map<C, String> myMap;

    public void assignVal()
    {
        myMap = new EnumMap<C, String>(C.class);
        myMap.put(C.c1, String.valueOf(1));
    }
}

Question: As you see myMap is tied to the enum C. I want to create a generic version of myMap, so I can assign any enum value in the class B.

I already went thru the stackoverflow post: How to implement enum with generics?

like image 243
curious Avatar asked Sep 14 '26 18:09

curious


1 Answers

You can't do this with EnumMap.

EnumMap requires a key of a single type — the constructor is there to enforce this by tying the generic type to a concrete type.

Under the hood it builds a cache of possible key values that it uses to enforce run-time type safety.

You'll need to use another type of map if you want to allow keys from your hierarchy.

like image 166
teppic Avatar answered Sep 16 '26 08:09

teppic