Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this not compile : List<List<String>> lss = new ArrayList<ArrayList<String>>(); [duplicate]

The below code :

List<List<String>> lss = new ArrayList<ArrayList<String>>();

causes this compile time error :

Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>>

to fix I change the code to :

List<ArrayList<String>> lss = new ArrayList<ArrayList<String>>();

Why is this error being thrown ? Is this because the generic type List in List<List<String>> is instantiated and since List is an interface this is not possible ?

like image 484
blue-sky Avatar asked Dec 01 '22 17:12

blue-sky


2 Answers

The problem is that type specifiers in generics do not (unless you tell it to) allow subclasses. You have to match exactly.

Try either:

List<List<String>> lss = new ArrayList<List<String>>();

or:

List<? extends List<String>> lss = new ArrayList<ArrayList<String>>();
like image 164
Jules Avatar answered Dec 31 '22 09:12

Jules


From http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

Note: Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no relationship to MyClass<B>, regardless of whether or not A and B are related. The common parent of MyClass<A> and MyClass<B> is Object.

enter image description here

like image 40
Majid Laissi Avatar answered Dec 31 '22 08:12

Majid Laissi