问题
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