为什么Java的Double.compare(double,double)实现了它的样子? [英] Why is Java's Double.compare(double, double) implemented the way it is?

查看:5155
本文介绍了为什么Java的Double.compare(double,double)实现了它的样子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在查看 compare(double,double)在Java标准库(6)中。它读为:

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) {
    if (d1 < d2)
        return -1;       // Neither val is NaN, thisVal is smaller
    if (d1 > d2)
        return 1;        // Neither val is NaN, thisVal is larger

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

编辑:Merits是一个非常糟糕的单词选择。我想知道这是如何工作的。

edit: "Merits" was a (very) bad choice of words. I wanted to know how this works.

推荐答案

@ Shoover的答案是正确的,但有一点比这更多。

@Shoover's answer is correct, but there is a bit more to it than this.

只要假设Java设计者决定实现 equals(...) double == 具有相同的语义>实例。这意味着 equals()对于包装的NaN将总是返回 false 。现在考虑如果您尝试在地图或集合中使用包装的NaN会发生什么。

Just suppose that the Java designers had decided to implement equals(...) and compare(...) with the same semantics as == on the wrapped double instances. This would mean that equals() would always return false for a wrapped NaN. Now consider what would happen if you tried to use a wrapped NaN in a Map or Collection.

List<Double> l = new ArrayList<Double>();
l.add(Double.NaN);
if (l.contains(Double.NaN)) {
    // this wont be executed.
}

Map<Object,String> m = new HashMap<Object,String>();
m.put(Double.NaN, "Hi mum");
if (m.get(Double.NaN) != null) {
    // this wont be executed.
}

没有什么意义!

因此,Java设计者决定(正确地IMO)对于我们今天这些Double方法的更复杂(但更直观)的定义。

So the Java designers decided (rightly IMO) on the more complicated (but more intuitive) definition for these Double methods that we have today.

这篇关于为什么Java的Double.compare(double,double)实现了它的样子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆