Double Compare NaN And Negative Zero

Sort doubles reliably with Double.compare: it treats NaN as largest and distinguishes -0.0 from 0.0, both of which break subtraction-based comparators.

JavaData Integrity

Code

snippet
import java.util.ArrayList;
import java.util.List;

public class DoubleOrdering {

    public static void main(String[] args) {
        List<Double> readings = new ArrayList<>(List.of(0.0, -0.0, Double.NaN, 3.5, -1.25));

        // Double.compare 是全序:NaN 大于一切,-0.0 与 0.0 可区分
        readings.sort(Double::compare);
        System.out.println(readings);

        // equals 与 == 的分歧:NaN 不等于自身,但装箱后 equals 相等
        System.out.println("== on NaN: " + (Double.NaN == Double.NaN));
        System.out.println("equals on NaN: " + Double.valueOf(Double.NaN).equals(Double.NaN));

        // -0.0 与 0.0 用 == 相等,但 compare 排出先后
        System.out.println("== on zeros: " + (-0.0 == 0.0));
        System.out.println("compare zeros: " + Double.compare(-0.0, 0.0));
    }
}

Inside the snippet

The snippet is organized around the class DoubleOrdering and the function main.

What to watch for

  • Self-sufficient by design — there is no registry and no lockfile entry.

Using it

The main signature, verbatim, is public static void main(String[] args)

Look for the == on NaN:, equals on NaN:, == on zeros: prefixes once the file starts running; each one ties a printed line to the step that produced it.

Key statements

readings.sort(Double::compare);

Interactive Tools for This Topic

FAQ

What does Double Compare NaN And Negative Zero print when run?
The script runs standalone; its 4 labeled outputs include `== on NaN:`, `equals on NaN:`, `== on zeros:`.