如何!=和==运算符在Java中使用整数? [英] How != and == operators work on Integers in Java?

查看:114
本文介绍了如何!=和==运算符在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");
    }
}

}

输出:

Output:


[ver1输出]

不同的对象< br>
有意义相等。

[ver1 output]
Different objects
Meaningfully equal.

[ver2输出]

等于对象

有意义相等

[ver2 output]
Equal Object
Meaningfully equal

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

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 将始终返回相同的引用。 整数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为true,false,字节或范围内的char \ u0000到\ u007f,或-128到127(含)之间的int或short数,然后让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.

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

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


较少内存限制的实现可能会缓存所有char和短值,以及-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天全站免登陆