The explanation is in the comments in the code. Java has double values for both 0.0
and -0.0
, as well as “not a number” (NaN
). You can’t use simple ==
operator for these values. Take a peek into the doubleToLongBits()
source and at the Javadoc for the Double.equals()
method:
Note that in most cases, for two
instances of classDouble
,d1
andd2
,
the value ofd1.equals(d2)
istrue
if
and only ifd1.doubleValue() == d2.doubleValue()
also has the value
true
. However,
there are two exceptions:
- If
d1
andd2
both representDouble.NaN
, then the equals method returnstrue
, even
thoughDouble.NaN == Double.NaN
has the valuefalse
.- If
d1
represents+0.0
whiled2
represents-0.0
, or vice versa, the equal test has the valuefalse
, even though+0.0 == -0.0
has the valuetrue
.This definition allows hash tables to operate properly.