I’m doing some experiments, trying to understand the issues surrounding returning generics. The following program runs without error and prints “FOO gets BAR” at the end. Can anyone explain why? The GetMap() member has unsafely cast a HashMap<Integer,Integer> to a Map<K,V>, which in the test case is a Map<String,String>. All my reading suggests I should get a ClassCastException, but I’m not getting one.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GenericTrial
{
public static <K,V> Map<K,V> GetMap()
{
return (Map<K,V>)new HashMap<Integer,Integer>();
}
public static void main(String[] args)
{
try
{
Map<String,String> m = GetMap();
m.put("FOO", "BAR");
System.out.println("FOO gets " + m.get("FOO"));
}
catch (Exception e)
{
System.out.println("Got exception");
}
}
}
Because of Java’s type erasure, there is no difference at runtime between a
Map<K, V>and aMap<T, U>.Generic types are a purely compile-time concept.