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
  • 176,041
  • 30
  • 275
  • 357
blue-sky
  • 51,962
  • 152
  • 427
  • 752

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,841
  • 9
  • 83
  • 130
  • 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
  • 19,188
  • 19
  • 68
  • 105
2

Same reason

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

wont work.

You can see this question for more details.

Community
  • 1
  • 1
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289