gpt4 book ai didi

java - 是否保证 new Integer(i) == i 在 Java 中?

转载 作者:IT老高 更新时间:2023-10-28 20:23:07 24 4
gpt4 key购买 nike

考虑以下代码段:

    int i = 99999999;
byte b = 99;
short s = 9999;
Integer ii = Integer.valueOf(9); // should be within cache

System.out.println(new Integer(i) == i); // "true"
System.out.println(new Integer(b) == b); // "true"
System.out.println(new Integer(s) == s); // "true"
System.out.println(new Integer(ii) == ii); // "false"

很明显为什么最后一行会总是输出 "false":我们使用 == 引用身份比较,以及 new 对象将 NEVER 成为现有对象的 ==

问题是关于前 3 行:这些比较 保证 是在原始 int 上与 Integer 自动拆箱?是否存在原语会被自动装箱并执行引用身份比较的情况? (这将是 false!)

最佳答案

是的。 JLS §5.6.2指定二进制数字提升的规则。部分:

When an operator applies binarynumeric promotion to a pair ofoperands, each of which must denote avalue that is convertible to a numerictype, the following rules apply, inorder, using widening conversion(§5.1.2) to convert operands asnecessary:

If any of the operands is of areference type, unboxing conversion(§5.1.8) is performed.

二进制数值提升适用于多个数值运算符,包括“数值相等运算符 == 和 !=”。

JLS §15.21.1 (数值等式运算符 == 和 !=)指定:

If the operands of an equalityoperator are both of numeric type, orone is of numeric type and the otheris convertible (§5.1.8) to numerictype, binary numeric promotion isperformed on the operands (§5.6.2).

相比之下,JLS §15.21.3 (引用等式运算符 == 和 !=)提供:

If the operands of an equalityoperator are both of either referencetype or the null type, then theoperation is object equality

这符合装箱和拆箱的普遍理解,只有在不匹配时才会这样做。

关于java - 是否保证 new Integer(i) == i 在 Java 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2831945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com