liveBook · Manning

Integer.compare

As explained in 100 Java Mistakes and How to Avoid Them

Integer.compare is a Java library method that compares two int values without computing their potentially overflowing difference.

Integer.compare is the safe way to compare two int values when implementing compareTo or a Comparator. Subtracting one value from another can overflow, reversing the intended ordering and violating the comparison contract. section 7.11

Why subtraction fails

With values near opposite ends of the int range, an expression such as i - o can wrap around and report the wrong ordering. A comparator may pass ordinary tests yet fail on larger inputs, including during sorting. section 7.11

Prefer these practices:

  • Replace primitive subtraction with Integer.compare(i, o.i), or use comparator methods such as comparing() and thenComparing(). section 7.11 section 7.15
  • Treat comparator correctness as essential: TimSort can detect violated invariants and throw IllegalArgumentException, although small or simple tests may not expose the defect. section 7.11
  • Do not test comparison results against one specific nonzero value; specifications permit any negative or positive result. section 7.15

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains overflow, comparison-contract violations, and TimSort failures, but does not detail Integer.compare internals.
Examples
Uses large opposite-sign integers, subtraction-based compareTo code, and a 32-element TimSort failure.
What it assumes
Assumes familiarity with Java int values, compareTo, comparators, and sorting collections.
What you can do after
Apply it by replacing subtraction with Integer.compare and by selecting comparator helpers for compound comparisons.
How it connects
Connects Integer.compare with compareTo, Comparator construction, sorting, and TimSort.

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.