这是我的代码:
Integer x=5;
int y=x+x;
System.out.println(y);
我的问题很简单。第一行显然正在发生一场拳击比赛。但在下一行中,是发生两次还是一次拆箱?我的问题实际上意味着:两个 Integer 实例 x 是否被拆箱、添加,然后存储在 int y 变量中,或者两个 Integer 作为 Integer 实例添加,然后结果被拆箱并存储? 附:请注意,上面的代码除了帮助我理解拆箱的概念之外没有其他目的。 非常感谢您的宝贵时间!
最佳答案
我想说发生了2次拆箱转化。
x
的类型肯定是 Integer
,并且算术表达式 x + x
需要将两个操作数拆箱。 JLS § 15.5指出
if the type of an expression is a primitive type, then the value of the expression is of that same primitive type.
此外,根据 § 15.18.2 ,
Binary numeric promotion is performed on the operands (§5.6.2).
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
The type of an additive expression on numeric operands is the promoted type of its operands.
因此,此类算术表达式的结果类型是原始数值类型,因此 x + x
生成 int
。
此结果存储到y
中,无需转换。
关于java - 正在进行多少次拆箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48584016/