为什么
Java在比较-0.0和0.0时不一致?将数字与-0 / 0进行比较的Java标准方法是什么?

我遇到过这个特别的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");
        }
    }
}

它打印以下内容:

== --> 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.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。