当使用==表示基元和盒装值时,自动装箱完成,或者取消装箱完成 [英] When using == for a primitive and a boxed value, is autoboxing done, or is unboxing done
问题描述
以下代码编译(使用Java 8):
The following code compiles (with Java 8):
Integer i1 = 1000;
int i2 = 1000;
boolean compared = (i1 == i2);
但是它做了什么?
Unbox i1
:
boolean compared = (i1.intvalue() == i2);
或方框 i2
:
boolean compared = (i1 == new Integer(i2));
所以它比较两个整数
对象(通过参考)或两个 int
变量值?
So does it compare two Integer
objects (by reference) or two int
variables by value?
请注意,对于某些数字,参考比较将产生正确的结果是因为Integer类维护的值在 -128
到 127
之间的内部缓存(另请参阅TheLostMind的注释) 。这就是我在我的例子中使用 1000
的原因以及为什么我特别询问有关拆箱/装箱而不是比较的结果。
Note that for some numbers the reference comparison will yield the correct result because the Integer class maintains an internal cache of values between -128
to 127
(see also the comment by TheLostMind). This is why I used 1000
in my example and why I specifically ask about the unboxing/boxing and not about the result of the comparison.
推荐答案
它在 JLS#15.21.1 :
如果相等运算符的操作数都是数字类型,或者一个是数字类型,另一个是可转换的(第5.1.8节)到数字类型,对操作数执行二进制数字提升(§5.6.2)。
If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).
和 JLS#5.6.2 :
当运算符将二进制数字提升应用于一对操作数时,每个操作数都是必须表示可转换为数字类型的值,以下规则适用:
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:
- 如果任何操作数是引用的类型,它需要进行拆箱转换
[...]
所以要回答你的问题,整数
被拆箱到 int
。
So to answer your question, the Integer
is unboxed into an int
.
这篇关于当使用==表示基元和盒装值时,自动装箱完成,或者取消装箱完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!