I would second what teppic said -- you cannot use EnumMap
generically with all subclasses of A
. It must be constructed with a specific concrete class. See the JavaDoc of EnumMap
https://docs.oracle.com/javase/7/docs/api/java/util/EnumMap.html
I see that you seems to have two options here
Use other types of Map implementations (e.g. HashMap
)
Map<A, String> myMap1 = new HashMap<>();
myMap1.put(C.c1, C.c1.name());
System.out.println(myMap1);
The output would be:
{c1=c1}
Implement yet another subclasses of A
so that you can use EnumMap
If, for some reasons, you really want to use EnumMap
, and you do not
want to implement all the values of C
, D
, E
into one enum, you still have
the following solution.
Implement a new subclasses of A
(let's call it SuperCde
in the following code example) that has all the possible values of C
, D
, and E
, and
it has a static method getSuperCde()
that serves as a bridge:
public static enum SuperCde implements A{
c1,c2,c3,
d1,d2,d3,
e1,e2,e3
;
public static SuperCde getSuperCde(A a) {
if (a instanceof C) {
C cValue = (C) a;
switch (cValue) {
case c1: return SuperCde.c1;
case c2: return SuperCde.c2;
case c3: return SuperCde.c3;
default: throw new IllegalArgumentException();
}
} else if (a instanceof D) {
D dValue = (D) a;
switch (dValue) {
case d1: return SuperCde.d1;
case d2: return SuperCde.d2;
case d3: return SuperCde.d3;
default: throw new IllegalArgumentException();
}
} else if (a instanceof E) {
E eValue = (E) a;
switch (eValue) {
case e1: return SuperCde.e1;
case e2: return SuperCde.e2;
case e3: return SuperCde.e3;
default: throw new IllegalArgumentException();
}
} else {
throw new IllegalArgumentException();
}
}
}
And then you can use the following code:
Map<SuperCde, String> myMap2 = new EnumMap<SuperCde, String>(SuperCde.class);
myMap2.put(SuperCde.getSuperCde(C.c1), C.c1.name());
System.out.println(myMap2);
The output would be:
{c1=c1}