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 Integer
s as elements, and LinkedList<integer>
is an object (with Integer
s 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?