The below line gives me error :
Incompatible Types. List<List<Integer>> output = new ArrayList<ArrayList<Integer>>();
What is the reason?
EDIT
I understand if I change my second ArrayList to List, it does not give me error. I want to know the reason of error though. Thanks
The correct writing should be: List<List<Integer>> ret = new ArrayList<List<Integer>> (); Since in this way, you can add not only ArrayList but also LinkedList to ret Show activity on this post. The reason is that generics are not covariant. Now List holds a Float, which is certainly bad. Same for your case.
List<List<Integer>> allsubsets is declared as List of List, but the implementation is unknown. Only you know the type of nested List is ArrayList, so either change foreach to use List<Integer> or manually cast your List<Integer> to ArrayList<> (this is not preferred)
If you had a List<List<Integer>> then you'd be able to add a LinkedList<Integer> to it. But you can't do this for an ArrayList<ArrayList<Integer>>, so the latter can't possibly be a type of List<List<Integer>>.
Show activity on this post. The correct writing should be: List<List<Integer>> ret = new ArrayList<List<Integer>> (); Since in this way, you can add not only ArrayList but also LinkedList to ret Show activity on this post.
This is a common misunderstanding when it comes to programming with generics, but it is an important concept to learn.
Box<Integer>
is not a subtype of Box even though Integer is a subtype of Number.
The correct writing should be: List<List<Integer>> ret = new ArrayList<List<Integer>>();
Since in this way, you can add not only ArrayList
but also LinkedList
to ret
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With