为什么
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.