【问题标题】:Is it safe to compare two `Integer` values with `==` in Java? [duplicate]在Java中将两个“整数”值与“==”进行比较是否安全? [复制]
【发布时间】:2019-08-05 15:07:03
【问题描述】:

我有这个 Java 代码:

public class Foo {
    public static void main(String[] args) {
         Integer x = 5;
         Integer y = 5;
         System.out.println(x == y);
    }
}

是否保证在控制台上打印true?我的意思是,它是按值(这是我需要做的)还是通过引用身份比较两个装箱整数?

另外,如果我将它们转换为像这样的未装箱整数会有什么不同

public class Foo {
    public static void main(String[] args) {
         Integer x = 5;
         Integer y = 5;
         System.out.println((int) x == (int) y);
    }
}

【问题讨论】:

  • 它通过引用身份比较它们。 -128127 范围内的整数被缓存,这就是为什么 Integer 实例有时是相同的引用。但是你最好使用equals
  • 问题是,如果我写 (int) x == (int) y IDE(我正在使用 intellijIdea)告诉我演员表是不必要的
  • 如果需要你可以使用x.intValue() == y.intValue(),但最好使用x.equals(y)
  • @oggioniw 如果其中一个可能为空,则需要对其进行空检查(或使用Objects.equals)。使用.equals.intValue()(int) all 可能会引发NullPointerException
  • @khelwood +1 建议使用Objects.equals

标签: java


【解决方案1】:

不,直接与对象比较不是正确的方法。您可以转换为int值并进行比较。

Java 实现

其中 value 的类型为 int。

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

【讨论】:

    【解决方案2】:

    不,这不是比较 Integer 对象的正确方法。您应该使用Integer.equals()Integer.compareTo() 方法。

    默认情况下,JVM 将缓存 [-128, 127] 范围内的 Integer 值(请参阅 java.lang.Integer.IntegerCache.high property),但不会缓存其他值:

    Integer x = 5000;
    Integer y = 5000;
    System.out.println(x == y); // false
    

    取消装箱到int 或调用Integer.intValue() 将创建一个int 原语,可以安全地与== 运算符进行比较。但是,取消装箱 null 将导致 NullPointerException

    【讨论】:

    • 如果我将它们转换为像 (int) x == (int) y 这样的未装箱整数会怎样?
    • 如需完整答案,请提及使用Objects.equals 作为commented by khelwood 作为空问题的解决方案。
    • 自 Java7 起缓存范围也是可配置的
    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多