Java 为什么Double.compare()会对数字进行两次比较

Java 为什么Double.compare()会对数字进行两次比较,java,double,Java,Double,我正在调试模式下通过F5查看Double.compare()实现(复制粘贴) 第二次比较的冗余性是什么?如果d1是类似0.0的数字,d2是NaN,那么d1d2也将为假,但这并不能使NaN等于d1。此外,如果d1为-0.0且d2为0.0,则d1d2也将为false,但0.0应大于-0.0 注释清楚地表明了这一点。如果d1是一个类似0.0的数字,d2是NaN,那么d1d2也将为假,但这并不能使NaN等于d1。此外,如果d1为-0.0且d2为0.0,则d1d2也将为false,但0.0应大于-0.0

我正在调试模式下通过
F5
查看
Double.compare()
实现(复制粘贴)


第二次比较的冗余性是什么?

如果
d1
是类似
0.0
的数字,
d2
NaN
,那么
d1
将为假,
d1>d2
也将为假,但这并不能使
NaN
等于
d1
。此外,如果
d1
-0.0
d2
0.0
,则
d1
将为
false
d1>d2
也将为false,但
0.0
应大于
-0.0


注释清楚地表明了这一点。

如果
d1
是一个类似
0.0
的数字,
d2
NaN
,那么
d1
将为假,
d1>d2
也将为假,但这并不能使
NaN
等于
d1
。此外,如果
d1
-0.0
d2
0.0
,则
d1
将为
false
d1>d2
也将为false,但
0.0
应大于
-0.0


注释非常清楚。

注释非常明确:这是为了处理一个棘手的案例。可以尝试Single.compare()注释非常明确:这是为了处理一个棘手的案例。可以尝试Single.compare()注释
public static int compare(double d1, double d2) {
    if (d1 < d2)
        return -1;           // Neither val is NaN, thisVal is smaller
    if (d1 > d2)
        return 1;            // Neither val is NaN, thisVal is larger

    // Cannot use doubleToRawLongBits because of possibility of NaNs.
    long thisBits = Double.doubleToLongBits(d1);
    long anotherBits = Double.doubleToLongBits(d2);

    return (thisBits == anotherBits ?  0 : // Values are equal
            (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
             1));                          // (0.0, -0.0) or (NaN, !NaN)
}
public static int compare(double d1, double d2) {
    if (d1 < d2)
        return -1;
    if (d1 > d2)
        return 1;
    return 0;
}
thisBits < anotherBits ? -1 : 1);