Java - 正负零的比较

Java - comparison of positive and negative zeros

为什么 Java 在比较 -0.0 和 +0.0 时不一致? Java 比较数字以说明 -0/+0 的标准方法是什么?

我遇到过这个问题:

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

它打印以下内容:

== --> same
equals --> different

我非常不喜欢你比较这两个值的方式会影响结果,我希望得到解释。

这种行为是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.

Java 语言规范:Numerical Comparison Operators <, <=, >, and >=

Positive zero and negative zero are considered equal.

Double.valueOf(+0.0) 和 Double.valueOf(-0.0) 具有不同的位表示。 Double.equals比较位表示。

你也可以使用Double.compare