java - 无与伦比的类型 : int and Number in java 8

标签 java compilation java-8 openjdk

假设我有以下代码:

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

如何解决这个问题:

  • 此构造是否有编译器选项以继续在 Java 8 中工作?
  • 我是否应该使用 instanceof 检查 Number 的所有子类和强制转换,然后逐个进行比较?这看起来很丑……
  • 其他建议?

最佳答案

这实际上是一个错误修正(参见 JDK-8013357 ):Java-7 的行为与 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 不可转换为数字类型),因此根据规范,它应该是一个编译时错误。

此更改在 Compatibility Guide for Java 8 中提到(搜索“原始”)。

请注意,虽然您的代码在 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();
}

关于java - 无与伦比的类型 : int and Number in java 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858024/

相关文章:

java - 在 Android 应用程序中设置最小堆大小的目的是什么?

java - 即使我们可以使用以下代码片段进行深度克隆,为什么我们还要实现 Cloneable

javascript - CoffeeScript - 空间问题

java - 为什么你永远不应该在可选的 java 对象上使用 synchronized

Java8 .getMethod() 与::getMethod

java - Android Studio LibGDX 游戏不显示障碍物和地板

delphi - 在 Delphi 中编译和构建有什么区别?

gcc - 编译/链接到开罗图书馆

java - 使用 Lambda 在 Java 中合并两个不同类型(字符串和整数)的排序列表

java - boost::crc_32_type 的 CRC 结果与 java.util.zip.CRC32 不同