[I vote to reopen this for the community. The question What are the reasons why Map.get(Object key) is not (fully) generic does indeed nail the root cause of the issue. But for me, Stack Overflow is about answering questions, accessing working sample code, and supporting specific instances of API usage -- not about creating a canon of unique root causes. I was not able to find the other post, perhaps due to its title. Enums were created to provide a safe alternative to named constants. This issue defeats that benefit -- without mention in the API and without a compiler warning. Why reduce the level of safety to below that of named constants? For enum users this question is useful -- it comes up as #1 on google.]
Is this supposed to compile? It does, even though I'm getting an enum member of a different type (EnumDelta) from an enumMap initialized with type EnumAlpha. I thought that as a generic type, EnumMap would guarantee type safety with respect to EnumAlpha.
import java.util.EnumMap;
class Enum {
static enum EnumAlpha { ALPHA, BETA; }
static enum EnumDelta { DELTA, EPSILON; }
static EnumMap<EnumAlpha, String> enumMap = null;
public static void main (String[] args) {
enumMap = new EnumMap<EnumAlpha, String>(EnumAlpha.class);
String string = "foo";
enumMap.put(EnumAlpha.ALPHA, string);
//why does this line compile?
System.out.println(enumMap.get(EnumDelta.DELTA));
}
}
Program outputs:
null