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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text Diff ComparisonCompare two text blocks line by line and visualize the differences with added, removed, and unchanged lines highlighted. Useful for reviewing changes and patches.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.