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.