为什么某些Integer对象的== true? [英] Why is == true for some Integer objects?

查看:144
本文介绍了为什么某些Integer对象的== true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

整数包装器对象仅在值127内共享相同的实例?

我从Khalid Mughal SCJP复制了以下程序片段,但我无法理解输出的

I have copied the following program snippet from the Khalid Mughal SCJP, but I am unable to
understand the output.

 public class RQ200_60 {
    public static void main(String[] args) {
        Integer i = -10;
        Integer j = -10;
        System.out.print(i==j);         // output: true -- why true?
        System.out.print(i.equals(j));  // output: true
        Integer n = 128;
        Integer m = 128;
        System.out.print(n==m);         // output: false
        System.out.print(n.equals(m));  // output: true
    }
}      

上述程序输出为true对于第一个print语句,但它应该给出false,因为它是与==关系运算符的引用比较。但第三次打印出现错误,我不明白这种不一致。

The above program giving output true for the first print statement but it supposed to give false because it is reference comparison with == relational operator. But third print gives false and I don't understand this inconsistency.

非常感谢解释!

推荐答案

在第一种情况下,对象 i j 都指向相同的缓存对象。默认情况下,-128和127之间的范围缓存为 Integer Object。我们可以使用 JVM参数 来增加范围

In the first case, both the objects i and j are pointing to the same cached object. By default, the range between -128 and 127 are cached as Integer Object. We can increase the range using JVM arguments

这篇关于为什么某些Integer对象的== true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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