Course contentsShow
← Java
Lesson 1326 of 2,87030. Comparable and ComparatorFree lesson

Using Integer.compare and Other Wrapper Comparisons

Discover the safe comparison methods provided by wrapper classes like Integer.compare and Double.compare.

Using Integer.compare and Other Wrapper Comparisons

You'll learn why wrapper classes provide safe comparison methods and how to use them instead of risky arithmetic.

The Danger of Subtraction

When implementing compareTo, you might be tempted to compare integers by subtracting them:

// DANGEROUS - can overflow!
public int compareTo(Person other) {
    return this.age - other.age;
}

This looks elegant, but it's a ticking time bomb. If this.age is a large positive number and other.age is a large negative number, the subtraction can overflow and produce the wrong sign, breaking your contract.

The Safe Alternative: Integer.compare

Java's wrapper classes provide built-in comparison methods that handle overflow correctly:

public int compareTo(Person other) {
    return Integer.compare(this.age, other.age);
}

Integer.compare(x, y) returns:

  • Negative if x < y
  • Zero if x == y
  • Positive if x > y

All without risk of overflow.

Other Wrapper Comparisons

Every numeric wrapper class offers the same safe method:

Double.compare(price1, price2)
Long.compare(timestamp1, timestamp2)
Short.compare(value1, value2)
Byte.compare(byte1, byte2)

Bonus: Double.compare and Float.compare also handle special values like NaN and infinities correctly, which arithmetic operations don't.

Example in Context

public class Employee implements Comparable<Employee> {
    private int id;
    private double salary;
    
    public int compareTo(Employee other) {
        int result = Integer.compare(this.id, other.id);
        if (result != 0) return result;
        return Double.compare(this.salary, other.salary);
    }
}

Key Takeaway: Always use Integer.compare(), Double.compare(), and similar wrapper methods when comparing primitive numeric fields—they're overflow-safe and handle edge cases correctly.