2

Edit:

Thanks for pointing me to the generic type invariant discussion. Looks like the problem is at the generic type part. List<E> where E is a generic type, in this case, E is List<Integer> which is an interface with Integers as elements, and LinkedList<integer> is an object (with Integers as elements) not an interface. So it does not work.

So this needs to be done in two steps. Am I understanding this correctly?

List<List<Integer>> outter_list = new LinkedList<List<Integer>>();
List<Integer> innder_list = new LinkedList<Integer>();

It's somewhat different than the parent child classes case. Since in this case, we are comparing an object implements the interface to the underlying interface.

I hope they would make this easier...

Original question:

This is from questions on LeetCode. A question may require you to write a method that returns a List<Integer>. I could do:

LinkedList<Integer> list;
//code to construct the list here.
return list;

And it works fine.

There is a question that requires to return a List<List<Integer>> and below

LinkedList<LinkedList<Integer>> list;
//code to construct the lists here.
return list;

this would not work and resulted in incompatible type error. I am curious why.

I had to use LinkedList<List<Integer>> in the first line of declaration in order for it to work. As to my understanding the LinkedList<LinkedList<Integer>> list; is a perfect fine object that implements List<List<Integer>>. Why is it incompatible?

Jesse Zhuang
  • 388
  • 1
  • 4
  • 14
  • Generics are not covarient, Check this question once http://stackoverflow.com/questions/18666710/why-are-arrays-covariant-but-generics-are-invariant – RP- Nov 08 '14 at 01:24
  • please let me know if I am understanding this correctly as in my later Edit. Thanks, – Jesse Zhuang Nov 08 '14 at 02:59
  • Your understanding is correct, you need to do this because of the type erasure. If you want your outer list to hold any type of `List`, then you need to use wildcards something like `List super List>`. Read more on type erasure and wildcard generics – RP- Nov 08 '14 at 03:06
  • thanks for replying, @Rp- . This was for leetCode question so I was not supposed to modify the return type. But it is good to be aware of the possibility of the wildcard. – Jesse Zhuang Nov 08 '14 at 03:10

0 Answers0