Comparator.compare()
and Comparable.compareTo()
implementations.
The following cases are reported:
0
for the same elements. Such a comparison method violates the contract
and can produce unpredictable results when equal elements are encountered. In particular,
sorting may fail with an exception on some data.Integer.MIN_VALUE
. While allowed by contract, it may be error-prone, as some call sites
may incorrectly invert the return value of comparison method using unary minus. In this case, Integer.MIN_VALUE
will stay negative.
Example:
Comparator<String> lambda =
(a, b) -> a.length() > b.length()
? 0
: Math.random() > 0.5 ? -1 : 1;