0

Recently I've been studying Generic Types and a little bit of Wildcards. I'm going to illustrate the problem with an example code:

    ArrayList<SuperClass> arraySuper = new ArrayList<>();
    ArrayList<SubClass> arraySub = new ArrayList<>();

    arraySuper.add(new SuperClass());
    arraySuper.add(new SubClass());

Where SuperClass obviously is the super class of Subclass. In this example SuperClass in the diamond operator means "SuperClass or its subclasses". This is reasonable. But here:

   static void doSomething(ArrayList<SuperClass> idk) {}

with

    doSomething(arraySuper);
    doSomething(arraySub);   // Compile Error

SuperClass means "only SuperClass and not its subclasses."

Why is there this difference? Thanks for all answers.

  • "In this example SuperClass in the diamond operator means "SuperClass or its subclasses"" no: it means "infer the type from context". You've already said it's an `ArrayList` on the left, so the compiler takes it to be the same on the right. And since all `Subclass` instances are also instances of `Superclass`, you can add them to a list accepting instances of `Superclass`. – Andy Turner Apr 02 '20 at 13:50
  • Oh, are you meaning ``? That's not the diamond operator: `<>` is the diamond operator. `` is a type parameter. – Andy Turner Apr 02 '20 at 13:55
  • @AndyTurner Sorry, my fault, then I mean the type parameter. But the question remains, why is there a difference? – der_daniel Apr 02 '20 at 14:37
  • @AndyTurner And thanks for your answer! – der_daniel Apr 02 '20 at 14:37

0 Answers0