【问题标题】:Why Comparison Of two Integer using == sometimes works and sometimes not? [duplicate]为什么使用 == 比较两个整数有时有效,有时无效? [复制]
【发布时间】:2015-08-30 15:32:50
【问题描述】:

我知道我在使用 == 时正在比较参考,这不是一个好主意,但我不明白为什么会发生这种情况。

Integer a=100;
Integer b=100;
Integer c=500;
Integer d=500;
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true

【问题讨论】:

标签: java types comparison


【解决方案1】:

正在缓存 -128 到 127 之间的整数值。

请看下面的源码:

private static class IntegerCache {
    private IntegerCache(){}

    static final Integer cache[] = new Integer[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Integer(i - 128);
    }
}

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache 
        return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
}

【讨论】:

  • a == b 返回 true 表示 a 和 b 引用同一个对象。 c == d 返回 false 表示 c 和 d 不是同一个对象(即使它们的 intValue 相同)
  • 是的,绝对正确 Mastov....最初我也很困惑...请删除与此帖子无关的 cmets。谢谢大家
  • 只是为了关闭这个线程(我有点用力强调),这是choosen response in duplicate question 中非常重要的事情:道德:当你感兴趣时不要比较整数引用基础 int 值。使用 .equals() 或先获取 int 值。
  • 是的,但这一点大家都清楚,甚至在问题中已经说明了!
【解决方案2】:

Java 语言规范说,至少 -128 到 127 的包装对象被 Integer.valueOf() 缓存和重用,自动装箱隐式使用。

【讨论】:

    【解决方案3】:

    -128 和 127 之间的整数被缓存(相同值的整数引用相同的 Object)。比较您的ab 引用返回true,因为它们是相同的Object。您的cd 不在该范围内,因此它们的参考比较返回false

    【讨论】:

      猜你喜欢
      • 2018-06-15
      • 2020-01-14
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 2010-10-24
      相关资源
      最近更新 更多