1

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.

takendarkk
  • 3,347
  • 8
  • 25
  • 37
J-bob
  • 8,380
  • 11
  • 52
  • 85
  • Generics - no. Raw types - yes. – PM 77-1 Jul 31 '17 at 20:29
  • Yes, there are lots of situations like this. Java has 'weak generics' (whatever the technical term is.) Certain IDEs (NetBeans) allow for turning on warnings or errors for these kinds of problems. – Dave Cousineau Jul 31 '17 at 20:29
  • JVM simply doesn't allow type mismatch operations to occur because java has very tight type safety – ja08prat Jul 31 '17 at 20:30
  • 5
    You should be getting a compiler warning that tells you that this is unsafe and why, and the compiler will be correct. – Louis Wasserman Jul 31 '17 at 20:31
  • 1
    Using raw types (or using generics incorrectly) can cause bad things? That's surprising. ... well, no, actually it isn't. – Tom Jul 31 '17 at 20:31

0 Answers0