我不明白为什么 java 不进行扩展然后自动装箱。
Integer i = (short) 10;
我认为会发生以下情况:
- 首先将转换从
10
缩小到short
。 short
将扩展为int
。int
然后会自动装箱到Integer
。
相反,这是一个编译错误。
示例 2:
短 x = 10;
整数 y = x;
这也失败了。
最佳答案
根据JLS, Section 5.2 ,处理赋值转换:
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
无法同时应用两种转换(加宽图元转换和装箱转换);此处只能应用一种转换,因此它必须导致错误。
解决方案是将 short
转换回 int
(转换转换),这将允许赋值转换为装箱转换:
Integer i = (int) (short) 10;
(或者在这里,首先不要将它转换为 short
。)
Integer i = 10;
关于Java:扩大和自动装箱转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935931/