Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Collections, From the Inside

    Comparable and Comparator: Defining "Order"

    Comparable<T> — one method, int compareTo(T other), implemented by the class itself. String, Integer and records you write can

    Chapter 7 of 113 min read

    The Plain Picture#

    • Comparable = a thing's natural order, built into it: numbers by size, words alphabetically.

    • Comparator = a sorting rule you hand over from outside: "sort the students by score, highest first, then by name".

    The Real Names#

    • Comparable<T> — one method, int compareTo(T other), implemented by the class itself. String, Integer and records you write can implement it. Returns negative / zero / positive (Classes, Objects and Memory Ch 6).

    • Comparator<T> — one method, int compare(T a, T b), written separately. You can have as many comparators as you like for one class.

    • Sorting uses them: Collections.sort(list) / list.sort(null) use natural order; list.sort(comparator) uses the rule you pass.

    • Java's object sort (TimSort) is stable: elements that compare equal keep their original relative order.

    Under the Hood#

    Building comparators — the modern, readable way:

    Java
    record Student(String name, int score, int age) {}
    
    st.sort(
        Comparator
            .comparingInt(Student::score) // by score...
            .reversed() // ...highest first
            .thenComparing(Student::name)
    ); // ties broken by name
    // [Aisha:200, Priya:200, Rahul:150, Vikram:110]

    Student::score means "the function that takes a student and returns score()" (a method reference — Modern Java).

    Sorting arrays of arrays — constantly needed for interval and coordinate problems:

    Java
    int[][] intervals = {
        { 5, 8 },
        { 1, 3 },
        { 2, 6 },
    };
    
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); // by start time
    // [[1, 3], [2, 6], [5, 8]]

    The overflow bug — never write (a, b) -> a - b:

    Java
    Integer[] big = { Integer.MIN_VALUE, 5, Integer.MAX_VALUE };
    
    Arrays.sort(big, (a, b) -> a - b); // [5, 2147483647, -2147483648]   ← WRONG ORDER
    
    Arrays.sort(big, Integer::compare); // [-2147483648, 5, 2147483647]   ← correct

    5 − MIN_VALUE overflows to a negative number (How Computers Work Ch 4.1), so the comparator lies. You'll see a - b in many online solutions; it works only when values are small. Always use Integer.compare(a, b) (or Long.compare, Double.compare).

    The comparator contract: consistent (same answer every time), antisymmetric (compare(a,b) and compare(b,a) have opposite signs), and transitive. Broken comparators can make Collections.sort throw "Comparison method violates its general contract!".

    Check yourself

    4 questions
    1

    Comparable vs Comparator?

    Show answer

    Comparable is the class's own natural order (compareTo); Comparator is a separate ordering rule (compare), and you can have many.

    2

    Write a comparator for students: highest score first, then youngest first.

    Show answer

    Comparator.comparingInt(Student::score).reversed().thenComparingInt(Student::age).

    3

    Why is (a, b) -> a - b dangerous?

    Show answer

    The subtraction can overflow for large values, giving the wrong sign and a wrong order; use Integer.compare.

    4

    What does "stable sort" mean?

    Show answer

    Elements that compare as equal keep their original relative order.