Why does this not compile : List<List<String>> lss = new ArrayList<ArrayList<String>>();
本问题已经有最佳答案,请猛点这里访问。
以下代码:
1 | List<List<String>> lss = new ArrayList<ArrayList<String>>(); |
导致此编译时错误:
1 | Type mismatch: cannot convert from ArrayList<ArrayList<String>> to List<List<String>> |
要修复,我将代码更改为:
1 | List<ArrayList<String>> lss = new ArrayList<ArrayList<String>>(); |
为什么会引发此错误?这是因为>
问题是泛型中的类型说明符不允许(除非您告诉它)子类。你必须精确匹配。
尝试:
1 | List<List<String>> lss = new ArrayList<List<String>>(); |
或:
1 | List<? extends List<String>> lss = new ArrayList<ArrayList<String>>(); |
来自http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html
Note: Given two concrete types A and B (for example, Number and
Integer),MyClass has no relationship toMyClass , regardless of
whether or not A and B are related. The common parent ofMyClass
andMyClass is Object.
同样的原因
1 | List<List> myList = new ArrayList<ArrayList>(); |
不会工作。
您可以查看此问题以了解更多详细信息。