为什么 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)
}
这个实现的优点是什么?
What are the merits of this implementation?
优点"是一个(非常)糟糕的词选择.我想知道这是如何工作的.
edit: "Merits" was a (very) bad choice of words. I wanted to know how this works.
推荐答案
@Shoover 的答案是正确的(阅读!),但除此之外还有更多内容.
@Shoover's answer is correct (read it!), but there is a bit more to it than this.
作为 javadoc for Double::equals
状态:
As the javadoc for Double::equals
states:
这个定义允许哈希表正常运行."
"This definition allows hash tables to operate properly."
假设 Java 设计者决定用与 ==<相同的语义来实现
equals(...)
和 compare(...)
/code> 在包装的 double
实例上.这意味着 equals()
将始终为包装的 NaN 返回 false
.现在考虑如果您尝试在 Map 或 Collection 中使用包装的 NaN 会发生什么.
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.
}
这样做没有多大意义!
可能存在其他异常,因为 -0.0
和 +0.0
具有不同的位模式,但根据 ==
是相等的.
Other anomalies would exist because -0.0
and +0.0
have different bit patterns but are equal according to ==
.
因此,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.
相关文章