【问题标题】:Why does comparison of two integers of MAX_VALUE fail in java? [duplicate]java - 为什么在java中比较两个MAX_VALUE整数会失败? [复制]
【发布时间】:2016-03-16 04:49:48
【问题描述】:

我在 Java 中有以下几行代码:

public class myProjects {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Integer d = Integer.MAX_VALUE;
    Integer e = Integer.MAX_VALUE;
    System.out.println(d);
    System.out.println(e);
    if(d == e){
        System.out.println("They are equal\n");

    }else {
        System.out.println("They are not equal\n");
    }
}

}

Output:
2147483647
2147483647
They are not equal

为什么它们即使具有相同的值也不相等?

【问题讨论】:

    标签: java


    【解决方案1】:

    Integer.MAX_VALUE 返回一个int。在执行Integer d = Integer.MAX_VALUE; 时,它会将int 通过Integer.valueOf 装箱到Integer

    由于默认情况下缓存来自 [-128, 127] valueOf 将为每个调用返回新实例。因此它们不是相同的引用。

    你可以在生成的字节码中看到这一点:

    public static void main(java.lang.String[]);
        Code:
           0: ldc           #3                  // int 2147483647
           2: invokestatic  #4                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
           5: astore_1
           6: ldc           #3                  // int 2147483647
           8: invokestatic  #4                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    

    以及Integer.valueOf的源代码:

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

    【讨论】:

    • 这有帮助。非常感谢
    【解决方案2】:

    您是在比较对象,而不是原语。

    您应该使用d.equals(e); 而不是d == e

    d == e 评估对象是否相同,而它们不是。

    【讨论】:

      【解决方案3】:

      简单地说,IntegerObject 而不是 primitive 值,

      要检查对象是否相等,您需要使用equals 方法

      例如

      if(d.equals(e)) {....}
      

      【讨论】:

        【解决方案4】:

        正如 sharonbn 在评论中提到的那样。

        尝试改变

        Integer d = Integer.MAX_VALUE;
        Integer e = Integer.MAX_VALUE;
        

        int d = Integer.MAX_VALUE;
        int e = Integer.MAX_VALUE;
        

        看看会发生什么。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-17
          • 1970-01-01
          • 2012-09-15
          • 2012-04-17
          • 2013-01-31
          相关资源
          最近更新 更多