为什么不编译:List>lss = new ArrayList>();

为什么不编译:List<List<String>>lss = new ArrayList<ArrayList<String>>();

问题描述:

以下代码:

List<List<String>> lss = new ArrayList<ArrayList<String>>();

导致此编译时错误:

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

为什么会抛出这个错误?这是因为 List> 中的泛型类型 List 被实例化了,并且因为 List 是一个接口,所以这是不可能的吗?

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 ?

问题是泛型中的类型说明符不允许(除非你告诉它)允许子类.你必须完全匹配.

The problem is that type specifiers in generics do not (unless you tell it to) allow subclasses. You have to match exactly.

尝试:

List<List<String>> lss = new ArrayList<List<String>>();

或:

List<? extends List<String>> lss = new ArrayList<ArrayList<String>>();