compareTo
/compare
may have unexpected results JAVA-W104839 itemStacks.sort((itemStack1, itemStack2) -> {
40 int c = Integer.compare(itemStack1.getType().ordinal(), itemStack2.getType().ordinal());
41 if (c == 0) {
42 c = -Integer.compare(itemStack1.getAmount(), itemStack2.getAmount());43 }
44 return c;
45 });
This code negates the return value of a compareTo
or compare
method. Avoid doing so, as it is both confusing and may lead to unexpected behavior.
This is a questionable or bad programming practice, since if the return value is Integer.MIN_VALUE
, negating the return value won't negate the sign of the result. Additionally, such code may confuse anybody who reads it.
Avoid negating the result of compareTo
or any compare
method.
if (-a.compareTo(b) > 0) {
// ...
}
Perform the intended operation directly, either by changing the operator, or reversing the order of the operands.
if (a.compareTo(b) < 0) {
// ...
}