Video in progress
What traps are there with NaN, -0.0 and Double.compare() when working with double?
NaN == NaN is false, but Double.valueOf(NaN).equals(NaN) is true; 0.0 == -0.0 is true, but equals says false. == follows IEEE 754, while equals/compare look at the bits, and in collections and sorting that difference causes bugs.
📖 Answer
double nan = 0.0 / 0.0;
nan == nan; // false
Double.valueOf(nan).equals(nan); // true
Double.compare(nan, 1.0); // 1: NaN is treated as the largest
0.0 == -0.0; // true
Double.valueOf(0.0).equals(-0.0); // false
Double.compare(0.0, -0.0); // 1
Why: the primitive == follows IEEE 754. equals and hashCode compare the bits through doubleToLongBits, otherwise you could add a NaN to a HashSet and never find it again.
Where it lets you down:
- Writing your own
compareToasa < b ? -1 : a > b ? 1 : 0: transitivity breaks wherever there's aNaN, andTimSortcan throw "Comparison method violates its general contract!". Always useDouble.compare. - A
doublecomponent in a record:equalsworks withDouble.comparesemantics, sonew P(0.0).equals(new P(-0.0))is false. - If a
NaNappears in a calculation, it "poisons" all the following operations and silently ends up in the DB or in JSON (Jackson writes it as the string"NaN"by default, so a client expecting a number fails, and standard JSON has noNaNnumber at all). Check withDouble.isNaN/isFiniteat the boundaries.
Sign up to mark studied questions and save your progress.