无法比较的类型:java 8 中的 int 和 Number

incomparable types: int and Number in java 8

假设我有以下代码:

class proba {
    boolean fun(Number n) {
        return n == null || 0 == n;
    }
}

使用 openjdk 7 (debian wheezy) 编译没有问题,但使用 openjdk 8 时编译失败,并出现以下错误(即使使用 -source 7):

proba.java:3: error: incomparable types: int and Number
    return n == null || 0 == n;
                          ^
1 error

如何解决这个问题:

这实际上是一个错误修复(参见 JDK-8013357): the Java-7 behavior contradicted the JLS §15.21:

The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error.

在你的情况下,一个操作数是数字类型,而另一个是引用类型(Number 不能转换为数字类型),所以它应该是一个 compile-time 错误,根据规范.

此更改在 Compatibility Guide for Java 8 中提及(搜索 "primitive")。

请注意,虽然您的代码在 Java-7 中编译,但它的工作方式有些奇怪:

System.out.println(new proba().fun(0)); // compiles, prints true
System.out.println(new proba().fun(0.0)); // compiles, prints false
System.out.println(new proba().fun(new Integer(0))); // compiles, prints false

这就是为什么 Java-7 将 0 提升为 Integer 对象(通过自动装箱),然后通过引用比较两个对象,这不太可能是您想要的。

要修复您的代码,您可以将 Number 转换为一些预定义的基本类型,例如 double:

boolean fun(Number n) {
    return n == null || 0 == n.doubleValue();
}

如果你想比较 Number 和 int - 调用 Number.intValue() 然后比较。