【问题标题】:== with Abstract datatypes, different results for the same kind of conditions [duplicate]== 具有抽象数据类型,相同条件的不同结果[重复]
【发布时间】:2012-08-10 23:03:14
【问题描述】:

可能重复:
Integer wrapper objects share the same instances only within the value 127?

public class test
{
  public static void main(String args[])
  {
    Integer a1=127;
    Integer a2=127;
    System.out.println(a1==a2); //output: true

    Integer b1=128;
    Integer b2=128;
    System.out.println(b1==b2); //output: false

    Long c1=127L;
    Long c2=127L;
    System.out.println(c1==c2); //  output: true

    Long d1=128L;
    Long d2=128L;
    System.out.println(d1==d2); //output: false 
  }
}

输出:

true
false
true
false

您也可以使用负值。当您观察带有值的输出时,它们的行为会有所不同。造成如此不同结果的原因是什么?

对于任何数字,范围应为 -127 到 +127,则 == 为真或为假。

(全部) 伙计们,对不起,这是一个拼写错误,我错误地把它当作原始的,但它是抽象的。对不起这个错误。现已更正...

【问题讨论】:

  • 那些不是原始数据类型。用intlong 试试,它会按预期运行。
  • 哦,这是我的最爱。它出现在 SO 某处的“最奇怪的代码行为”线程中。

标签: java memory memory-management jvm shared-memory


【解决方案1】:

整数不是原始的,它是一个对象。如果你使用intlong,你只会得到true

你得到这个结果的原因是整数被缓存在 -128 和 127 之间的值,所以Integer i = 127 将总是返回相同的引用。 Integer j = 128 不一定会这样做。然后您需要使用equals 来测试底层int 是否相等。

这是在Java Language Specification #5.1.7 中定义的。

请注意,超出该范围 [-128; 的值的行为127] 未定义:

例如,内存限制较少的实现可能会缓存所有 char 和 short 值,以及 -32K 到 +32K 范围内的 int 和 long 值。

【讨论】:

    【解决方案2】:

    Integer 不是原始类型,而是包装类型。见:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

    【讨论】:

      【解决方案3】:

      Integer 是对象(包装类),而不是原始类型

      最好像a1.intValue() == a2. intValue() 那样进行比较,而不是(或)equals()

      【讨论】:

      • 对象之间的比较有一个equals方法。
      【解决方案4】:

      首先,整数不是基元(int 是)。但是要回答为什么会发生这种情况,是因为在 Integer 实现中发现了一个内部缓存:

       /**
       * Cache to support the object identity semantics of autoboxing for values between 
       * -128 and 127 (inclusive) as required by JLS.
       *
       * The cache is initialized on first usage. During VM initialization the
       * getAndRemoveCacheProperties method may be used to get and remove any system
       * properites that configure the cache size. At this time, the size of the
       * cache may be controlled by the vm option -XX:AutoBoxCacheMax=<size>.
       */
      

      因此,本质上,当您比较两个已缓存的整数时,您是在将同一个对象与其自身进行比较,因此 == 返回 true,但是当您比较高于 127 或低于 -127 的整数(非缓存整数)时,您正在比较两个不同的 Integer 实例。

      如果您使用 equals 或 compareTo 方法,您将得到 期望看到的内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-17
        • 2018-12-01
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        • 2020-12-15
        • 2016-08-30
        • 1970-01-01
        相关资源
        最近更新 更多