javacomparisonnumbers

Comparing Numbers in Java


In Java, all numeric types extend from java.lang.Number. Would it be a good idea to have a method like the following:

public boolean areEqual(Number first, Number second) {
    if (first != null && second != null) {
        return first.equals(second);
    }
}

I'm concerned about cases where a double 2.00000 does not equal an int 2. Are these handled by the built-in equals? If not, is there any way to write a simple number compare function in java? (external libraries such as apache commons are ok)


Solution

  • A Double is NEVER equals to an Integer. Moreover, a double is not the same as a Double.

    Java has primitive types and reference types. The truly numeric types in Java do not extend from Number, because they're primitives.

    You may want to consider a system where you're not mixing types, because that usually will cause a lot of trouble with implicit/explicit conversions that may/may not lose information, etc.

    Related questions

    On int vs Integer:

    On Number comparison:

    See also


    On mixed-type computation

    Mixed-type computation is the subject of at least 4 puzzles in Java Puzzlers.

    Here are various excerpts:

    it is generally best to avoid mixed-type computations [...] because they are inherently confusing [...] Nowhere is this more apparent than in conditional expressions. Mixed-type comparisons are always confusing because the system is forced to promote one operand to match the type of the other. The conversion is invisible and may not yield the results that you expect

    Prescription: Avoid computations that mix integral and floating-point types. Prefer integral arithmetic to floating-point.