【问题标题】:How is it possible that 127==127 while 128!=128? [duplicate]127==127 而 128!=128 怎么可能? [复制]
【发布时间】:2015-03-11 09:54:44
【问题描述】:
Integer v1_1 = 127;
Integer v1_2 = 127;

Integer v2_1 = 128;
Integer v2_2 = 128;

System.out.println(v1_1 == v1_2);//true
System.out.println(v2_1 == v2_2);//false

为什么第二个表达式是false

我无法弄清楚该值如何影响比较结果。

【问题讨论】:

  • 永远不要使用== 来比较对象。 (Java 进行“装箱”的方式让新手非常困惑——比根本没有它更糟糕,IMO。)
  • 我知道我从来没有那样使用它,但我只是想知道它怎么可能,现在我明白为什么了。

标签: java


【解决方案1】:

因为 Integer 类型 interns 的值(通过静态类 IntegerCache)从 -128 到 127。

【讨论】:

    【解决方案2】:

    因为 Integer 类在内部使用 IntegerCache,它将对象从 -128 缓存到 127。例如当您调用 valueOf 时,Integer 类会像这样检查值是否在缓存中

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

    如果缓存中存在该值,那么您将获得相同的对象。这就是为什么

    System.out.println(v1_1 == v1_2);//returns true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 2020-11-12
      • 2023-03-31
      • 1970-01-01
      • 2023-02-14
      • 2018-06-09
      • 2019-09-23
      相关资源
      最近更新 更多