Java通用列表< List<扩展Number>> [英] Java Generic List<List<? extends Number>>

查看:143
本文介绍了Java通用列表< List<扩展Number>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展Number>> aList = new ArrayList< List< Number>>();

即使这样也行:

 列表与LT ;?扩展Number> aList = new ArrayList< Number>(); 

编译器错误信息是:


类型不匹配:无法从ArrayList转换< List< Number>>列出<列表<在Java中,如果扩展数字>>



解决方案

code> Car 是一个派生类 Vehicle ,那么我们可以把所有 Cars 车辆; a Car 车辆。然而, Cars List 不是 List $ c> of 车辆。我们说 List< Car> List< Vehicle> <不是协变 / b>

Java需要你明确地告诉它何时想使用协变和与通配符相冲突,这些通配符表示为标记。看看你的问题发生在哪里:

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


How come in java we cannot do:

List<List<? extends Number>> aList = new ArrayList<List<Number>>();

Even though this is OK:

List<? extends Number> aList = new ArrayList<Number>();

Compiler error message is:

Type mismatch: cannot convert from ArrayList<List<Number>> to List<List<? extends Number>>

解决方案

In Java, if 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>.

Java requires you to explicitly tell it when you would like to use covariance and contravariance with wildcards, represented by the ? token. Take a look at where your problem happens:

List<List<? extends Number>> l = new ArrayList<List<Number>>();
//        ----------------                          ------
// 
// "? extends Number" matched by "Number". Success!

The inner 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.

However, the combined inner type parameter 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>>();

这篇关于Java通用列表&lt; List&lt;扩展Number&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆