liveBook · Manning

Comparator invariant

As explained in 100 Java Mistakes and How to Avoid Them

A comparator invariant is a property of comparison results, such as transitivity, that must remain consistent across compared values.

A comparator invariant is a consistency property—such as transitivity—that comparison results must preserve across values. Subtracting integers in compareTo can violate it through overflow, producing incorrect ordering. section 7.11

The subtraction trap

With values 2,000,000,000, 0, and −2,000,000,000, `return i - o.i` can report contradictory ordering because the subtraction overflows. Replace it with `Integer.compare(i, o.i)` or an explicit three-way comparison.

Prevent comparator-invariant failures by:

  • Test large values, larger collections, and sorted collections such as TreeSet; violations can corrupt collection behavior, not merely sorting order. section 7.11

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains overflow, hidden failures, TimSort checks, collection-size effects, and TreeSet consequences, but does not develop a general testing procedure.
Examples
Uses overflowing IntObj comparisons, a 32-element random array, and TreeSet membership and removal examples.
What you can do after
Apply it via Integer.compare, test larger inputs, and diagnose comparator failures in sorting and TreeSet behavior.
How it connects
Connects comparator invariants with integer overflow, Comparable, sorting algorithms, TimSort, and TreeSet.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.