Comparable vs Comparator

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Comparable: Modifies the class itself. Defines the Default Natural Sorting Order of an object (e.g., sorting employees by ID).
  • Comparator: A separate class/lambda. Defines Custom Sorting Orders (e.g., sorting employees by Salary, then by Name).

Concept

If you call Collections.sort(employeeList), Java doesn’t know how to sort them. Does it sort by Name? Age? Salary?
If the Employee class implements Comparable<Employee>, it must override compareTo(). This tells Java the “default” way to sort employees forever.

However, what if you usually sort by ID, but on one specific webpage, you want to sort by Salary? You cannot change the compareTo() method because that affects the whole application.
Instead, you create a Comparator (often as a lambda: (e1, e2) -> e1.getSalary() - e2.getSalary()) and pass it to Collections.sort(employeeList, myComparator). This temporarily overrides the default sorting behavior.

Examples

import java.util.*;

// 1. COMPARABLE (The Default Order)
class Employee implements Comparable<Employee> {
    int id;
    String name;
    int salary;

    public Employee(int id, String name, int salary) {
        this.id = id; this.name = name; this.salary = salary;
    }

    @Override
    public int compareTo(Employee other) {
        // Default sort: Ascending by ID
        return Integer.compare(this.id, other.id); 
    }
}

public class SortingDemo {
    public static void main(String[] args) {
        List<Employee> list = Arrays.asList(
            new Employee(3, "Alice", 90000),
            new Employee(1, "Bob", 120000)
        );

        // Uses the Comparable implementation (Sorts by ID)
        Collections.sort(list); 

        // 2. COMPARATOR (Custom Order)
        // Uses a Comparator to temporarily sort by Salary descending!
        Collections.sort(list, (e1, e2) -> Integer.compare(e2.salary, e1.salary));
        
        // Modern Java 8+ Comparator chaining
        list.sort(Comparator.comparing(Employee::getName).reversed());
    }
}

Interview Questions

Q: How does the compareTo(T o) method work?
A: It compares the current object (this) with the specified object (o).

  • Returns a negative integer if this is less than o.
  • Returns zero if this is equal to o.
  • Returns a positive integer if this is greater than o.

Q: Can I sort a List of Strings without providing a Comparator?
A: Yes. The String class (and most standard Java classes like Integer, Date, etc.) already implements the Comparable interface out of the box. Strings naturally sort alphabetically. You only need a Comparator if you want to sort Strings in a non-natural way (e.g., sorting Strings by their length instead of alphabetically).