4

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 ?

rgettman
  • 172,063
  • 28
  • 262
  • 343
blue-sky
  • 49,326
  • 140
  • 393
  • 691

3 Answers3

13

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>>();
Jules
  • 14,135
  • 8
  • 79
  • 128
  • Exactly, everything in <> braces should match. Only class before <> braces can be subtype. – Pawel Dec 20 '13 at 11:31
3

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

Majid Laissi
  • 18,348
  • 18
  • 64
  • 104
2

Same reason

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

wont work.

You can see this question for more details.

Community
  • 1
  • 1
Aniket Thakur
  • 63,511
  • 37
  • 265
  • 281