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)— comparesthistootherComparator:int compare(T o1, T o2)— compares two separate objects
Return Values
The compare method follows the same contract as compareTo:
- Negative integer:
o1comes beforeo2 - Zero:
o1equalso2in ordering - Positive integer:
o1comes aftero2
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.