Comparable vs Comparator in Java: Key Differences Explained
Comparable is an interface that lets an object describe its own natural ordering; Comparator is a separate object that imposes a custom ordering on other objects without changing them.
Think of Comparable as a student writing “sort me by last name” on her own paper, while Comparator is the teacher shuffling a pile of tests by grade, then later by first name—same data, different rules, no edits to the student.
Key Differences
Comparable uses compareTo inside the class and affects the class’s identity. Comparator’s compare method lives outside, so you can plug multiple orderings into the same class at runtime.
Which One Should You Choose?
Pick Comparable for one natural order; use Comparator when you need many or you can’t modify the source code. In legacy APIs, Comparator keeps you flexible without touching the original class.
Can I use both on the same class?
Yes. The class implements Comparable for its default order, and you supply extra Comparator instances for alternative sorts.
Does Comparator break object identity?
No. It only changes how collections view the object, never the object’s state or equals/hashCode contract.
Why does TreeSet sometimes ignore my Comparator?
If elements already implement Comparable, TreeSet falls back to it unless you pass the Comparator in the constructor.