0

I was trying to understand subtyping with Generics and while playing with code I came across below scenario and I am not able to understand why this is happening:

I can do:

public <L> L doSomethingL(List<L> list) {
    list.add(list.get(0));
    return list.get(1);
}

And call this method as:

System.out.println(aa.doSomethingL(new ArrayList<String>() {{ add("a"); add("b"); }})); // prints "b"

But I cannot do:

    List<L> objectList = null;
    List<String> stringList = new ArrayList<String>();
    objectList = stringList; // compilation error

In my understanding, in both the cases finally I am assigning an object of ArrayList of type String.

pjj
  • 1,853
  • 1
  • 12
  • 34
  • There's a minor note unrelated to your actual question: The modern (since Java 9) easy way to have a fixed-content list is to simply use [`List.of("a", "b")`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html#of(E,E)). It's slightly different from your example, because the list is fixed-size, but for sample programs like this it's clearly better. It also avoids the [problematic double brace initialization](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java). – Joachim Sauer Oct 25 '21 at 14:03

0 Answers0