java - 正在进行多少次拆箱?

标签 java integer int boxing unboxing

这是我的代码:

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/

相关文章:

java - 单元测试: Testing a class which has an outside method

java - 优化匹配2个巨大文本文件的java代码

java - 在Java中将常量字符串附加到变量字符串的最有效方法?

python - 整数到字节而不在python中使用struct

c - 为什么 getpagesize() 返回一个 int?

python - 将此字符串格式化为列表的最简单但不是最快的方法是什么? Python

python - 在 Python 中除以长整型会返回错误的答案

Java CompilerThread 占用更多 CPU 使用率

python - 当由 '..' Python 分隔时,将两个整数附加到列表

python - 如何将字符串中的数字引用转换为 Python 中的整数?