Comparing Primitive Fields: Subtraction Pitfalls
You'll learn why subtracting primitive values in compareTo can silently produce wrong results due to integer overflow.
The Tempting Shortcut
When implementing compareTo for classes with primitive numeric fields, it's tempting to use subtraction as a quick comparison trick:
public class Product implements Comparable<Product> {
private int price;
@Override
public int compareTo(Product other) {
return this.price - other.price; // Dangerous!
}
}
This looks elegant: if this.price is larger, you get a positive number; if smaller, negative; if equal, zero. Perfect, right?
The Integer Overflow Trap
Wrong. Subtraction can overflow, causing the sign to flip unexpectedly.
Consider comparing price = 2_000_000_000 with other.price = -2_000_000_000. The subtraction produces 4_000_000_000, which exceeds Integer.MAX_VALUE (about 2.1 billion). Java wraps this to a large negative number, making your method claim the first product is less than the second—completely backwards!
The Safe Approach
Use explicit comparison instead:
@Override
public int compareTo(Product other) {
return Integer.compare(this.price, other.price); // Safe
}
Or manually:
if (this.price < other.price) return -1;
if (this.price > other.price) return 1;
return 0;
Both approaches correctly handle all integer values, including edge cases near Integer.MIN_VALUE and Integer.MAX_VALUE.
Key Takeaway: Never subtract primitives in compareTo—use Integer.compare(), Double.compare(), or explicit if-statements to avoid overflow bugs that break sorting and tree-based collections.