2 回答

TA貢獻1804條經驗 獲得超7個贊
在 equals/hashcode 方法中推薦使用的方法[需要引用]是分別使用Double.doubleToLongBits()
和Double.hashcode()
。
這是因為如果哈希碼不同,則 equals 合約要求兩個輸入的計算結果為“不同”。反之則沒有限制。
(注意:事實證明Double.compare()
內部使用,doubleToLongBits()
但 API 沒有指定。因此我不會推薦它。另一方面,hashCode()
確實指定它使用doubleToLongBits()
。)
實際例子:
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
Vector2d other = (Vector2d)obj;
return Double.doubleToLongBits(x) == Double.doubleToLongBits(other.x) &&
Double.doubleToLongBits(y) == Double.doubleToLongBits(other.y);
}
@Override
public int hashCode() {
int hash = 0x811C9DC5;
hash ^= Double.hashCode(x);
hash *= 0x01000193;
hash ^= Double.hashCode(y);
hash *= 0x01000193;
return hash;
}

TA貢獻1820條經驗 獲得超2個贊
double
值不應該用作建立對象相等性及其hashcode的組件。
這是因為浮點數存在固有的不精確性,并且人為地雙飽和+/-Infinity
為了說明這個問題:
System.out.println(Double.compare(0.1d + 0.2d, 0.3d)); System.out.println(Double.compare(Math.pow(3e27d, 127d), 17e256d / 7e-128d));
印刷:
1 0
...這轉化為以下兩個錯誤陳述:
0.1+0.2>0.3
(3 * 1027)127 == 17 * 10256 / (7 * 10-128)
因此,你的軟件會讓你對兩個不相等的相等數字或兩個非常大或非常小的不相等數字相等采取行動。
添加回答
舉報