Casting Nested Generic Types

送分小仙女□ 提交于 2021-02-19 05:24:06

问题


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:


回答1:


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



来源:https://stackoverflow.com/questions/66037939/casting-nested-generic-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!