Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incompatible types List of List and ArrayList of ArrayList

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

like image 889
Kraken Avatar asked Jul 17 '14 06:07

Kraken


People also ask

How to add List<Integer> to ArrayList?

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.

How to implement List<Integer> with allsubsets in Java?

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)

Is it possible to add a LinkedList<Integer> to an ArrayList<ArrayList>?

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>>.

How to add ArrayList to ret show activity in Java?

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.


2 Answers

From Generics, Inheritance, and Subtypes

This is a common misunderstanding when it comes to programming with generics, but it is an important concept to learn.

enter image description here

Box<Integer> is not a subtype of Box even though Integer is a subtype of Number.

like image 74
earthmover Avatar answered Sep 24 '22 13:09

earthmover


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

like image 33
spiralmoon Avatar answered Sep 25 '22 13:09

spiralmoon