!= 和 == 运算符如何处理 Java 中的整数? [英] How != and == operators work on Integers in Java?

查看:33
本文介绍了!= 和 == 运算符如何处理 Java 中的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码让我很困惑,因为它提供了两种不同的输出.代码在 jdk 1.7 上测试过.

The following code seemed really confusing to me since it provided two different outputs.The code was tested on 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 输出]
不同的对象
有意义的平等.

[ver1 output]
Different objects
Meaningfully equal.

[ver2 输出]
相等对象
有意义的平等

[ver2 output]
Equal Object
Meaningfully equal

为什么 == 和 != 测试会为 ver1() 和 ver2() 生成不同的结果,而相同的数字远小于 Integer.MAX_VALUE?是否可以断定 == 检查大于 127 的数字(对于像代码中显示的 Integer 这样的包装类)完全是浪费时间?

Why the == and != testing produces different results for ver1() and ver2() for same number much less than the Integer.MAX_VALUE? Can it be concluded that == checking for numbers greater than 127 (for wrapper classes like Integer as shown in the code) is totally waste of time?

推荐答案

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

Integers are cached for values between -128 and 127 so Integer i = 127 will always return the same reference. Integer j = 128 will not necessarily do so. You will then need to use equals to test for equality of the underlying int.

这是 Java 语言规范:

如果被装箱的值 p 是真、假、一个字节或 u0000 到 u007f 范围内的一个字符,或者一个介于 -128 和 127(包括)之间的 int 或短数字,则令 r1 和 r2 为p 的任意两次装箱转换的结果.r1 == r2 总是如此.

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 次调用可能会返回相同的引用(不保证):

But 2 calls to Integer j = 128 might return the same reference (not guaranteed):

例如,内存限制较少的实现可能会缓存所有 char 和 short 值,以及 -32K 到 +32K 范围内的 int 和 long 值.

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 中的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆