Why is Java's Double.compare(double, double) implemented the way it is?

后端 未结 4 1157
情书的邮戳
情书的邮戳 2020-12-01 03:26

I was looking at the implementation of compare(double, double) in the Java standard library (6). It reads:

public static int compare(double d1, double d2) {
         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 04:13

    The explanation is in the comments in the code. Java has double values for both 0.0 and -0.0, as well as "not a number" (NaN). You can't use simple == operator for these values. Take a peek into the doubleToLongBits() source and at the Javadoc for the Double.equals() method:

    Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if

    d1.doubleValue() == d2.doubleValue()
    

    also has the value true. However, there are two exceptions:

    • If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN == Double.NaN has the value false.
    • 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.

提交回复
热议问题