Java通用列表< List<扩展Number>> [英] Java Generic List<List<? extends Number>>
问题描述
扩展Number>> aList = new ArrayList< List< Number>>();
即使这样也行:
列表与LT ;?扩展Number> aList = new ArrayList< Number>();
编译器错误信息是:
类型不匹配:无法从ArrayList转换< List< Number>>列出<列表<在Java中,如果
扩展数字>>
code> Car 是一个派生类 Java需要你明确地告诉它何时想使用协变和与通配符相冲突,这些通配符表示为 内部 但是,组合的内部类型参数 How come in java we cannot do: Even though this is OK: Compiler error message is:
In Java, if Java requires you to explicitly tell it when you would like to use covariance and contravariance with wildcards, represented by the The inner However, the combined inner type parameter
这篇关于Java通用列表< List<扩展Number>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Vehicle
,那么我们可以把所有 Cars
为车辆
; a Car
是车辆
。然而, Cars
的 List 不是
List $ c> $ c> of
车辆
。我们说 List< Car>
与 List< Vehicle>
<不是协变 / b>
?
标记。看看你的问题发生在哪里:
List< List<扩展Number>> l = new ArrayList< List< Number>>();
// ---------------- ------
//
//?extends Number匹配Number 。成功!
列表< ;?因为
Number
的确扩展了 Number
,所以它匹配?extends Number
。到现在为止还挺好。接下来是什么?
列表<列表< ;?扩展Number>> l = new ArrayList< List< Number>>();
// ---------------------- ------------
//
//List< ;? extends Number>不符合List< Number>。这些是
//不同的类型和协方差没有用通配符指定。
//失败。
List <?> extends Number>
不与 List< Number>
相匹配;类型必须完全相同。另一个通配符会告诉Java,这个组合类型也应该是协变的:
List< ;?扩展List <?扩展Number>> l = new ArrayList< List< Number>>();
List<List<? extends Number>> aList = new ArrayList<List<Number>>();
List<? extends Number> aList = new ArrayList<Number>();
Type mismatch: cannot convert from ArrayList<List<Number>> to List<List<? extends Number>>
Car
is a derived class of Vehicle
, then we can treat all Cars
as Vehicles
; a Car
is a Vehicle
. However, a List
of Cars
is not also a List
of Vehicles
. We say that List<Car>
is not covariant with List<Vehicle>
.?
token. Take a look at where your problem happens:List<List<? extends Number>> l = new ArrayList<List<Number>>();
// ---------------- ------
//
// "? extends Number" matched by "Number". Success!
List<? extends Number>
works because Number
does indeed extend Number
, so it matches "? extends Number
". So far, so good. What's next?List<List<? extends Number>> l = new ArrayList<List<Number>>();
// ---------------------- ------------
//
// "List<? extends Number>" not matched by "List<Number>". These are
// different types and covariance is not specified with a wildcard.
// Failure.
List<? extends Number>
is not matched by List<Number>
; the types must be exactly identical. Another wildcard will tell Java that this combined type should also be covariant:List<? extends List<? extends Number>> l = new ArrayList<List<Number>>();