我正在尝试理解 JLS 的示例。
It is a compile-time error if the chain of conversions contains two parametrized types that are not in the subtype relation.
An example of such an illegal chain would be:
Integer, Comparable<Integer>, Comparable, Comparable<String>
The first three elements of the chain are related by widening reference conversion, while the last entry is derived from its predecessor by unchecked conversion. However, this is not a valid assignment conversion, because the chain contains two parametrized types,
Comparable<Integer>
andComparable<String>
, that are not subtypes.
我们在什么条件下才能得到这条链?有人可以举一些更详细的例子吗?
最佳答案
我相信我已经明白了一些道理。
赋值上下文适用于赋值表达式。
在表达式中
Integer integerValue = 42;
Comparable<Integer> comparableInteger = integerValue;
整数文字42
可以分配给 Integer
类型的变量通过拳击转换。 Integer
类型的值可以分配给 Comparable<Integer>
类型的变量通过扩大引用转换。
在下面的表达式中
Comparable raw = comparableInteger;
Comparable<Integer>
类型的值可以分配给 Comparable
类型的变量通过扩大引用转换。
但是你不能这样做
Comparable<String> comparableString = integerValue;
因为这需要从 Comparable
进行未经检查的转换至Comparable<String>
,这不一定是坏事,除非
the chain of conversions contains two parametrized types that are not in the subtype relation
你本来可以做到的
Comparable raw = comparableInteger;
Comparable<String> parameterized = raw;
这将使用未经检查的转换(当您尝试调用 ClassCastException
时,可能会在运行时使用 compareTo
)。但是,在编译时没有问题,因为转换链很简单
Comparable, Comparable<String>
这是允许的。
关于java - JLS:第 5.2 节赋值转换(转换链),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28227967/