Comparator.compare
or Comparable.compareTo
is compared with
a specific non-zero constant.
By contract, these methods can return any positive number (not just 1) or any negative number (not just -1),
so comparing against particular numbers is bad practice. Some widely used comparison methods (e.g. String.compareTo
)
actually return values outside of the [-1..1] range, so such a comparison may cause incorrect program behavior.
Example:
void validate(String s1, String s2) {
// Comparing to 1 is incorrect
if (s1.compareTo(s2) == 1) {
throw new IllegalArgumentException("Incorrect order");
}
}
After the quick-fix is applied:
void validate(String s1, String s2) {
if (s1.compareTo(s2) > 0) {
throw new IllegalArgumentException("Incorrect order");
}
}
New in 2017.2