Java:加宽和自动装箱转换问题 [英] Java: Widening and autoboxing conversion issue
问题描述
我不明白为什么 java 不进行加宽然后自动装箱.
I don't get why java doesn't do the widening and then autoboxing.
Integer i = (short) 10;
我认为会发生以下情况:
I would think the following would take place:
- 首先将转换范围从
10
缩小到short
. short
然后会扩展为int
.int
然后会自动装箱为Integer
.
- Narrowing conversion first from
10
toshort
. short
would then widen toint
.int
would then autobox toInteger
.
相反,这是一个编译错误.
Instead it's a compilation error.
示例 2:
短 x = 10;
整数 y = x;
Short x = 10;
Integer y = x;
这也失败了.
推荐答案
根据JLS,第 5.2 节,处理赋值转换:
分配上下文允许使用以下之一:
Assignment contexts allow the use of one of the following:
身份转换(第 5.1.1 节)
an identity conversion (§5.1.1)
扩大原始转换(第 5.1.2 节)
a widening primitive conversion (§5.1.2)
扩大参考转换(第 5.1.5 节)
a widening reference conversion (§5.1.5)
装箱转换(第 5.1.7 节),可选后跟加宽参考转换
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
拆箱转换(第 5.1.8 节),可选后跟扩展原始转换.
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
不能同时应用两次转换(拓宽基元转换和装箱转换);此处只能应用一次转换,因此必须导致错误.
It is unable to apply two conversions at once (widening primitive conversion and boxing conversion); only one conversion can apply here, so it has to result in an error.
解决方案是将 short
转换回 int
(转换转换),这将允许赋值转换为装箱转换:
The solution would be to cast the short
back to an int
(a casting conversion), which would allow the assignment conversion to be a boxing conversion:
Integer i = (int) (short) 10;
(或者在这里,首先不要将其转换为 short
.)
(Or here, don't cast it to short
in the first place.)
Integer i = 10;
这篇关于Java:加宽和自动装箱转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!