我正在研究Java标准库(6)中compare(double,double)的实现.它写道:
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)
}
Run Code Online (Sandbox Code Playgroud)
这个实现的优点是什么?
编辑:"优点"是一个(非常)糟糕的选择.我想知道它是如何工作的.
Foo如果double成员在另一个对象的给定范围内,则认为类的对象是相等的.由于浮点运算,可以容易地引入这样的错误.
该方法 isDoubleEquals和doubleArrayEquals的部分相等,但合同规定哈希码必须是相等的对象相同的会照顾.双精度的默认哈希码不会将close值映射到相同的值,因此为匹配双精度数获取相同哈希值的好方法是什么?
public class Foo {
double[] values;
public Foo(double[] values) {
this.values = values;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
//TODO Arrays.hashCode will not work with the contract
result = prime * result + Arrays.hashCode(values);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Foo other = …Run Code Online (Sandbox Code Playgroud)