1

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?

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
Roy Li
  • 511
  • 1
  • 6
  • 14
  • @JBNizet I have a feeling that, this is not the exact dupe. – Suresh Atta Oct 08 '15 at 12:34
  • It is: the OP tries to initialize a List 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

1 Answers1

1

The first way was syntactically incorrect and correct is

    List<LinkedList<String>> result = new LinkedList<LinkedList<String>>();

And in second case, you are probably using JDK 7 or + where type inference happening with diamond operator.

To understand fully read Type Inference for Generic Instance Creation

For example, consider the following variable declaration:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):

Map<String, List<String>> myMap = new HashMap<>();
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307