Java通用列表<列表<?扩展数>> [英] Java Generic List&lt;List&lt;? extends Number&gt;&gt;

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

问题描述

在java中我们怎么做不到:

How come in java we cannot do:

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

尽管这没问题:

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

编译器错误信息是:

类型不匹配:无法从 ArrayList> 转换到列表<列表>

推荐答案

在Java中,如果CarVehicle的派生类,那么我们可以处理所有CarsVehicles;CarVehicle.然而,CarsList 并不也是VehiclesList.我们说ListList不协变.

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 要求您明确告诉它何时希望使用通配符的协方差和逆变,由 ? 标记表示.看看您的问题发生在哪里:

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!

内部List 起作用是因为 Number 确实扩展了 Number,所以它匹配? extends Number".到现在为止还挺好.下一步是什么?

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.

但是,组合内部类型参数ListList 不匹配;类型必须完全相同.另一个通配符会告诉 Java 这种组合类型也应该是协变的:

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通用列表<列表<?扩展数>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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