javagenericsunchecked-cast

Why does creating SimpleImmutableMap cause unchecked cast warning?


In the following pretty simple code:

public static void test(Map<Externalizable, Externalizable> t){
    for(Map.Entry<Externalizable, Externalizable> e : t.entrySet()){
      //The next line causes unchecked cast warning
      Object o = new AbstractMap.SimpleImmutableEntry(e.getKey(), e.getValue());
    }
  }

DEMO

Why? The AbstractMap.SimpleImmutableMap is a generic class. What's wrong?


Solution

  • Because you're using the raw type. Instead, use the diamond operator

    Object o = new AbstractMap.SimpleImmutableEntry<>(e.getKey(), e.getValue());