Java - comparing positive and negative zeros

Why is Java incompatible when comparing -0.0 and +0.0? What is the standard Java method for comparing numbers with a -0 / + 0 account?

I came across 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"); } } } 

He prints the following:

 == --> same equals --> different 

I really dislike the fact that how you compare these two values ​​affects the result, and I would like an explanation.

+6
source share
2 answers

This behavior is really documented :

If d1 represents +0.0, while d2 represents -0.0, or vice versa, the equal test is false, although the value +0.0 == - 0.0 is true. This definition allows hash tables to work correctly.

+10
source

Java Language Specification: Numerical Comparison Operators <, <=,> and> =

Positive zero and negative zero are considered equal.

Double.valueOf (+0.0) and Double.valueOf (-0.0) have different bit representations. Double.equals compares the representation of bits.

You can also use Double.compare

+1
source

All Articles