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
