Generics are knowingly meant for stronger type checking at compile time. However, while studying the official Java tutorial, I ran into this:
However, in some cases the compiler knows that a type parameter is always valid and allows the cast. For example:
List<String> l1 = ...;
ArrayList<String> l2 = (ArrayList<String>)l1; // OK
from http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#cannotCast.
I've tried and tested this (which fully reflects the documentation):
List<String> l1 = new LinkedList<String>();
ArrayList<String> l2 = (ArrayList<String>)l1; // OK
Although everything is pretty explicit (no assignment to an Object
variable, no wilcarding, etc), the compiler fails to predict the runtime error that shows up afterwards:
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.util.ArrayList
100% puzzled.