铸造嵌套泛型类型 [英] Casting Nested Generic Types

查看:56
本文介绍了铸造嵌套泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Java中将 List< Number> 强制转换为 List< Double> 是非法的,因为 List< Double> 不是 List< Number> 的子类型:

 列表< Number>list1 =新的ArrayList<>();List< Double>list2 =(List< Double>)list1;//不可转换的类型 

基于这种理解,我希望强制转换 List< ;?是违法的?将List< Number>> 扩展到 List< List< Double>> ,因为我认为 List< Double> 不属于由 List< Number> 给出的一系列类型.但是,此强制转换实际上是有效的,带有未经检查的强制转换警告:

 列表< ;?扩展List< Number>>list3 =新的ArrayList<>();List< List< Double>>list4 =(List< List< Double>>)list3;//未经检查的强制转换警告,但合法 

当上面的第一个演员表是非法的时,我该如何推断 List< Double> 属于 List< Number> 给出的类型族?/p>

在Intellij中使用javac 1.8.0_144:

解决方案

我不知道您使用的是什么工具来编译它,但是我没有从<代码> 8 到 16 .

这是非法的:

 列表< ;?扩展List< Number>>list3 =新的ArrayList<>();List< List< Double>>list4 =(List< List< Double>))list3; 

出于明显的原因.?扩展List< Number 不可能是 List< Double> 的超类型.

I understand that it is illegal in Java to cast a List<Number> to a List<Double>, since List<Double> is not a subtype of List<Number>:

    List<Number> list1 = new ArrayList<>();
    List<Double> list2 = (List<Double>) list1;  // inconvertible types

With this understanding I would expect that it is also illegal to cast a List<? extends List<Number>> to a List<List<Double>>, since I would think that List<Double> does not belong to the family of types given by List<Number>. However, this cast is actually valid, with an unchecked cast warning:

    List<? extends List<Number>> list3 = new ArrayList<>();
    List<List<Double>> list4 = (List<List<Double>>) list3;  // unchecked cast warning, but legal

How can I go about reasoning that List<Double> belongs to the family of types given by List<Number>, when the first cast above is illegal?

Using javac 1.8.0_144 in Intellij:

解决方案

I do not know what tool you are using to compile this, but I have not found one jdk that compile this, from 8 to 16.

This is illegal:

List<? extends List<Number>> list3 = new ArrayList<>();
List<List<Double>> list4 = (List<List<Double>>) list3;

for obvious reasons. ? extends List<Number can't possibly be a super-type of List<Double>.

这篇关于铸造嵌套泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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