Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - comparison of positive and negative zeros

Why is Java inconsistent in comparing -0.0 and +0.0? What is the Java standard method for comparing numbers to account for -0/+0?

I have encountered this particular bugaboo:

public class ZeroCompare {
    public static void main(String[] args) {
        if ( 0.0 == -0.0 ) {
            System.out.println("== --> same");
        } else {
            System.out.println("== --> different");
        }

        if ( new Double(0.0).equals( -0.0 ) ) {
            System.out.println("equals --> same");
        } else {
            System.out.println("equals --> different");
        }
    }
}

It prints the following:

== --> same
equals --> different

I strongly dislike the fact that how you compare these two values affects the outcome and I'd love for an explanation.

like image 889
Curds Avatar asked Aug 14 '15 12:08

Curds


1 Answers

This behaviour is actually documented:

If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0==-0.0 has the value true. This definition allows hash tables to operate properly.

like image 58
Tunaki Avatar answered Sep 28 '22 12:09

Tunaki