I needed to implement a function that has return type of List<List<String>>
and I tried lots of ways to instantiate the variable to return:
This does not work:
List<List<String>> result = new LinkedList<LinkedList<String>>();
error: incompatible types: LinkedList<LinkedList<String>> cannot be converted to List<List<String>>
Finally, this worked:
List<List<String>> result = new LinkedList<>();
Compiler is fine with this and the code works well.
However, I don't understand why the first statement does not work and why the second one does.
Can someone please explain?
with a List, where LinkedList is a subtype of List. Same problem as trying to initialize a List with a List, where Dog is a subtype of Animal. The dupe explains why that is invalid.
– JB Nizet Oct 08 '15 at 12:36