Incomparable types: int and Number in java 8

Suppose I have the following code:

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

This compiles without problems using openjdk 7 (debian wheezy), but when using openjdk 8, the following error fails to compile (even when using-source 7):

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

How to get around this:

  • Is there a compiler option for this construct to continue working in java 8?
  • Should I do a lot of consecutive ifs with checking the instances of all subclasses of Number and casting, and then compare one by one? It seems ugly ...
  • Other offers?
+4
source share
2 answers

(. JDK-8013357): Java-7 JLS §15.21:

, (. 5.1.8), boolean boolean , , null. .

, - (Number ), .

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 ( autoboxing), , , .

, Number double:

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

Number int-call Number.intValue(), .

+2

Source: https://habr.com/ru/post/1624808/


All Articles