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

久未见 提交于 2019-12-19 03:39:05

问题


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 ?


回答1:


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>>();



回答2:


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.




回答3:


Same reason

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

wont work.

You can see this question for more details.



来源:https://stackoverflow.com/questions/20702635/why-does-this-not-compile-listliststring-lss-new-arraylistarrayliststr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!