Comparator subtraction can overflow
Returning a - b from compare can overflow and reverse the ordering for extreme integers. Use Integer.compare or Comparator.comparingInt instead.
Good to see "Comparator subtraction can overflow" written down. Handy reference for anyone working with java / sorting.
Subtracting two ints in compare can wrap around when the difference exceeds the int range, flipping the sign. Integer.compare avoids the arithmetic entirely and is safe for all values.
A subtraction inside a comparator overflows for extreme values, so the sign of the result can invert. Integer.compare or Comparator.comparingInt performs the comparison without subtracting.
Comparators built on subtraction break near the limits of the int range, where the result wraps. Delegating to Integer.compare keeps the ordering correct across the full range.
Appreciate the write-up on "Comparator subtraction can overflow". Useful for anyone using java / sorting.
Good to see "Comparator subtraction can overflow" written down. Handy reference for anyone working with java / sorting.
Specific and to the point: "Comparator subtraction can overflow". Worth a look if you touch java / sorting.
"Comparator subtraction can overflow" is a useful thing to know about with java / sorting. Thanks for sharing it.