0
public class Generic<T> {

    public static void main(String[] args) {
        Generic g = new Generic();
        List<Integer> integerList = new ArrayList<>();
        integerList.add(42);
        g.f(integerList);
        System.out.println(integerList);
    }

    void f(List<String> stringList){
        stringList.add("hello");
    }
}

Executing this code will COMPILE and print [42, hello]

I'm passing my List<Integer> integerList to a List<String> stringList and the compiler is fine with it. Why? Isn't the compiler suppose to check this sort of things? Line with g.f(integerList); should throw a compile error. It's not.

ddreian
  • 1,766
  • 5
  • 21
  • 29
  • The compiler is indeed raising errors for this code. Can't reproduce your outcome. – ernest_k Nov 28 '19 at 15:23
  • For me it compiles with warnings. You should probably check the warnings. – khelwood Nov 28 '19 at 15:24
  • 1
    Interesting that the compiler errors if the `` type is removed, even though it is not used. And it errors if you specify a type for your generic instance `g`. But when you use a raw version of the generic type `Generic`, it seems to forget to do type checking on `f`, even though the type `T` is irrelevant to that. Weird quirk. – khelwood Nov 28 '19 at 15:25
  • What IDE do you use? What is java -version? I tried with 8 and 11 and both produce "Note: Generic.java uses unchecked or unsafe operations." warning, but produce .class though – Woworks Nov 28 '19 at 15:33
  • `class Generic {` should be `class Generic {`. Now you create an unsafe `Generic g` and the compiler no longer checks for generic typing: for backward compatibility. – Joop Eggen Nov 28 '19 at 15:46
  • Latest IntelliJ + OpenJDK12 from Zulu – ddreian Nov 28 '19 at 15:49

0 Answers0