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

Code below:

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 does this error occur? Is it because the generic type instance is List<List<String>>created and since List is an interface, is this not possible?

+4
source share
3 answers

The problem is that type specifiers in generics do not allow (unless you specify this) subclasses to be allowed. 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>>();
+13
source

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

. A B (, Integer), MyClass<A> MyClass<B>, , A B. MyClass<A> MyClass<B> - .

enter image description here

+3

List<List> myList = new ArrayList<ArrayList>();

.

.

+2

All Articles