When I am using an Enum as a type in Map, I am not getting a compile time error if I use a key whose type is different. For example in the code snippet below, I expected a compile time error when I tried accessing the map with a key whose type is String.
Why does generic not provide compile time safety when using generics in Map? When I try to insert an entry compile time check works.
With List this does not seem to be the case as I get a compile time error.
Consider the code sample below
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestEnumGeneric{
enum Sample{
A,B
}
enum Sample2 {
C,D
}
Map<Sample,String> someMap = new HashMap<Sample, String>();
Map<String,String> someOtherMap = new HashMap<String, String>();
List<Sample> someList = new ArrayList<Sample>();
public void testMapWithEnum() {
String value = someMap.get("123");
value = someMap.get(Sample2.C);
String value2 = someOtherMap.get(1);
//someMap.put("123","123");
//someList.add("123");
}
}