在比较Java中的整数包装器时,为什么128 == 128 false但127 == 127为真? [英] Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?

查看:203
本文介绍了在比较Java中的整数包装器时,为什么128 == 128 false但127 == 127为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class D {
    public static void main(String args[]) {
        Integer b2=128;
        Integer b3=128;
        System.out.println(b2==b3);
    }
}

输出:

false







class D {
    public static void main(String args[]) {
        Integer b2=127;
        Integer b3=127;
        System.out.println(b2==b3);
    }
}

输出:

true

注:以下数字 - 128和127是真的。

Note: Numbers between -128 and 127 are true.

推荐答案

在Java中编译数字文字并将其分配给整数(大写<$ c) $ c> I )编译器发出:

When you compile a number literal in Java and assign it to a Integer (capital I) the compiler emits:

Integer b2 =Integer.valueOf(127)

使用自动装箱时也会生成此行代码。

This line of code is also generated when you use autoboxing.

valueOf ,使某些数字合并,并为小于128的值返回相同的实例。

valueOf is implemented such that certain numbers are "pooled", and it returns the same instance for values smaller than 128.

从java 1.6源代码,第621行:

From the java 1.6 source code, line 621:

public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

的价值可以使用系统属性配置为另一个值。

The value of high can be configured to another value, with the system property.


-Djava.lang.Integer.IntegerCache.high = 999

-Djava.lang.Integer.IntegerCache.high=999

如果您使用该系统属性运行程序,它将输出true!

If you run your program with that system property, it will output true!

明显的结论是:永远不要依赖两个相同的引用,总是将它们与 .equals()方法进行比较。

The obvious conclusion: never rely on two references being identical, always compare them with .equals() method.

所以 b2.equals(b3)将为所有逻辑上相等的b2,b3值打印为真。

So b2.equals(b3) will print true for all logically equal values of b2,b3.

注意由于性能原因,整数缓存不存在,而是符合 JLS,第5.1.7节;必须为-128到127的值提供对象标识。

Note that Integer cache is not there for performance reasons, but rather to comform to the JLS, section 5.1.7; object identity must be given for values -128 to 127 inclusive.

Integer#valueOf(int)也记录了这种行为:


通过缓存频繁请求的值,此方法可能会显着提高空间和时间性能。此方法将始终缓存-128到127(包括端点)范围内的值,并可以缓存此范围之外的其他值。

this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

这篇关于在比较Java中的整数包装器时,为什么128 == 128 false但127 == 127为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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