問題描述
我正在查看 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.
這篇關于為什么 Java 的 Double.compare(double, double) 是這樣實現的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!