1

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");
    }
}
rixmath
  • 121
  • 6

1 Answers1

2

The signature of Map.get is

V get(Object key);

So it accepts any Object but only returns V. There is nothing wrong at compile time with your usage of get.

NetBeans warns about this usage:

Suspicious call to java.util.Map.get: Given object cannot contain instances of String (expected Sample)

The signature of Map.put is

V put(K key, V value);

So you must use proper types.

Edit:

To quote the JavaDoc:

If this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null.

It only matters that key.equals(k), they don't have to be of the same type.