3

I have a class named A (without generics), then if you look at inside the main method, everything is fine.

class A {

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        staticMethod(stringList); //DOES NOT COMPILE 
        new A().instanceMethod(stringList); //DOES NOT COMPILE
    }

    static void staticMethod(List<Integer> aList) { }

    void instanceMethod(List<Integer> aList) { }
}

But when I have the class A with a generic,

class A<T> {

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        staticMethod(stringList); //DOES NOT COMPILE 
        new A().instanceMethod(stringList); //**DOES COMPILE!!**
    }

    static void staticMethod(List<Integer> aList) { }

    void instanceMethod(List<Integer> aList) { }
}

I don't understand, how the raw usage of the class' instance make it compilable ?

Thank you.

  • 4
    Because using raw types erases *all* type related information from that object. So it sees it as `void instanceMethod(List aList)`. – RealSkeptic Jul 01 '20 at 15:42
  • 4
    Congratulations, you've stumbled over the horror that is the reason why you **really** don't want to use raw types. They *look* harmless enough at first (all you lose is the type information) until you realize that you lose **all** generics on *any* of its methods, even if they are unrelated to the type parameter of the class. – Joachim Sauer Jul 01 '20 at 15:49

0 Answers0