It appears that I have found a case where you can break Java's type safety using generics. Observe the following code:
import java.util.ArrayList;
import java.util.List;
public class Test {
public static List<Integer> aMethod(){
List list = new ArrayList();
list.add("this is not an int");
return list;
}
public static void main(String[] args) {
List<Integer> aList = aMethod();
System.out.println(aList.get(0) + 1);
}
}
The above code is perfectly legal according to Java JDK version 1.8.0_144. Notice that aMethod
purports to return a List<Integer>
but does not complain that I'm returning a List
without a type specified for the generic. Indeed, that list contains a string.
I am able to compile the code, and not surprisingly, when I run the main method I get
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
because I'm trying to add a String
to an int
. Is this a bug in the JDK? It seems like a huge oversight.