I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastExcepti
Java generics use type erasure, meaning those parameterized types aren't retained at runtime so this is perfectly legal:
List list = new ArrayList();
list.put("abcd");
List list2 = (List)list;
list2.add(3);
because the compiled bytecode looks more like this:
List list = new ArrayList();
list.put("abcd");
List list2 = list;
list2.add(3); // auto-boxed to new Integer(3)
Java generics are simply syntactic sugar on casting Objects.