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

The Comparator Interface: Purpose and Function Signature

Learn what Comparator is, when to use it instead of Comparable, and understand the compare(T o1, T o2) method signature.

The Comparator Interface: Purpose and Function Signature

What you'll learn: The role of Comparator<T> and how its compare method differs from Comparable's compareTo.

Why Comparator Exists

You've already learned that Comparable defines a class's natural ordering—the default way objects are sorted. But what if you need multiple sorting strategies? Or what if you're working with a class you didn't write and can't add Comparable to?

This is where Comparator shines. Think of Comparator as an external judge that can compare two objects without modifying the objects themselves. While Comparable is like asking an object "how do you compare to this other one?", Comparator is like asking a third-party expert "how do these two objects compare?"

The Comparator Interface

public interface Comparator<T> {
    int compare(T o1, T o2);
    // other methods exist, but compare is the core
}

Notice the key difference:

  • Comparable: int compareTo(T other) — compares this to other
  • Comparator: int compare(T o1, T o2) — compares two separate objects

Return Values

The compare method follows the same contract as compareTo:

  • Negative integer: o1 comes before o2
  • Zero: o1 equals o2 in ordering
  • Positive integer: o1 comes after o2

When to Use Comparator

Use Comparator when you need:

  • An alternative ordering (sort employees by salary or by hire date)
  • To sort classes you don't control (like library classes)
  • Multiple different orderings for the same type

Key Takeaway: Comparator<T> provides external, flexible sorting logic through the compare(T o1, T o2) method, allowing multiple orderings without modifying the class being sorted.