Short answer: Eclipse uses Double.doubleToLongBits because that's what Double.equals does:
The result is true
if and only if the argument is not null
and is a Double object that represents a doubl
e that has the same value as the double
represented by this object. For this purpose, two double
values are considered to be the same if and only if the method doubleToLongBits(double)
returns the identical long
value when applied to each.
Long answer: the JLS specifies a few differences between Double.equals and ==. For one difference specified in JLS 4.2.3 and JLS 15.21.1:
Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0
is true
and the result of 0.0>-0.0
is false
. But other operations can distinguish positive and negative zero; for example, 1.0/0.0
has the value positive infinity, while the value of 1.0/-0.0
is negative infinity.
Another regards NaN
:
If either operand is NaN, then the result of ==
is false
but the result of !=
is true
.
Indeed, the test x!=x
is true
if and only if the value of x is NaN.
As you can see, it's possible for two double values to compare with ==
but actually correspond to different behavior when used in math and hash tables. Thus, when writing a generated equality method, Eclipse makes the assumption that two doubles are only equal if and only if all operations that can be done to them are identical, or (equivalently) if they were autoboxed and compared with their equals
methods. This is particularly important if switching between double
and Double
—it would be particularly unexpected for equality properties to differ there.
Of course, you're free to drift from that assumption: Regardless of whether it's a good idea, you may assign special cases to any of the many possible NaN representations, in which case Double.doubleToRawLongBits()
would be a better match for your equals
and hashCode
methods. By the same token, your use case might treat objects with +0.0 and -0.0 as equivalent and guarantee that NaN values are not possible, in which case a raw ==
comparison may work better for equals
(but at which point emulating the same criteria for hashCode
becomes difficult).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…