gpt4 book ai didi

java - Java 中 != 和 == 运算符如何处理整数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:51:08 24 4
gpt4 key购买 nike

以下代码对我来说确实很困惑,因为它提供了两种不同的输出。该代码在 jdk 1.7 上进行了测试。

public class NotEq {

public static void main(String[] args) {

ver1();
System.out.println();
ver2();
}

public static void ver1() {
Integer a = 128;
Integer b = 128;

if (a == b) {
System.out.println("Equal Object");
}

if (a != b) {
System.out.println("Different objects");
}

if (a.equals(b)) {
System.out.println("Meaningfully equal.");
}
}

public static void ver2() {
Integer i1 = 127;
Integer i2 = 127;
if (i1 == i2) {
System.out.println("Equal Object");
}

if (i1 != i2){
System.out.println("Different objects");
}
if (i1.equals(i2)){
System.out.println("Meaningfully equal");
}
}

}

输出:

[ver1 output]
Different objects
Meaningfully equal.

[ver2 output]
Equal Object
Meaningfully equal

为什么对于比 Integer.MAX_VALUE 小得多的相同数字,== 和 != 测试会对 ver1() 和 ver2() 产生不同的结果?是否可以得出结论 == 检查大于 127 的数字(对于代码中所示的 Integer 等包装类)完全是浪费时间?

最佳答案

缓存 -128 到 127 之间的整数,因此 Integer i = 127 将始终返回相同的引用。 Integer j = 128 不一定会这样做。然后,您需要使用 equals 来测试底层 int 的相等性。

这是 Java Language Specification 的一部分:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

但是对 Integer j = 128 的 2 次调用可能会返回相同的引用(不保证):

Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

关于java - Java 中 != 和 == 运算符如何处理整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41817905/

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