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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With