Returning MIN_VALUE From compareTo()
ID |
java.compareto_min_value |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports return Integer.MIN_VALUE (or Long.MIN_VALUE) inside compareTo() methods. Negating MIN_VALUE overflows back to MIN_VALUE, which breaks any code that computes -compareTo() to reverse sort order.
Rationale
Integer.MIN_VALUE is -2147483648. Its negation overflows to itself: -Integer.MIN_VALUE == Integer.MIN_VALUE. Sorting algorithms, Comparator.reversed(), and manual sign-flipping all rely on -compareTo() yielding the opposite sign. When compareTo() returns MIN_VALUE, this invariant is violated.
// Bad - negation overflows
public int compareTo(Foo other) {
if (this.x < other.x) return Integer.MIN_VALUE;
return 0;
}
Remediation
Return -1, 0, or 1, or use Integer.compare().
// Good
public int compareTo(Foo other) {
return Integer.compare(this.x, other.x);
}