Comparable vs Comparator in Java
Fast recall
Quick revision
Core answer
Understanding of natural ordering vs external ordering strategies, and how they integrate with Collections.sort and TreeMap
Confusing the return value contract (negative/zero/positive) or forgetting that Comparator can be a lambda since Java 8
Mention Comparator.comparing(), thenComparing(), and reversed() chaining. Also note that violating the equals-consistency rule with Comparator in a TreeMap can cause surprising behavior.
Interview-ready guide
Interview answer
Comparable defines the natural ordering of a class from within; Comparator defines external orderings without modifying the original class.
Comparable:
- Implemented in the class itself via
compareTo() - Used by
TreeMap,TreeSet, andCollections.sort()as the default ordering - Should be consistent with
equals()— TreeSet usescompareTo()for equality, soa.compareTo(b)==0but!a.equals(b)silently treats them as duplicates
Comparator (Java 8 fluent API):
Comparator.comparing(Employee::getDept).thenComparing(Employee::getSalary, reverseOrder())— sorts by dept ascending, salary descending in one line- Use
comparingInt(),comparingLong(),comparingDouble()for primitives — avoids autoboxing on every comparison nullsFirst()/nullsLast()for explicit null handling
Gotcha:
reversed()flips the entire chain, not just the last key — to reverse only salary within each department, passreverseOrder()to that specificthenComparing()
I recommend implementing Comparable for the obvious natural order and using Comparator for everything else.
Comparable vs Comparator in Java
Direct Answer
Comparable defines an object's natural ordering via compareTo — implemented in the class itself. Comparator defines an external, ad-hoc ordering — passed as a strategy. Use Comparable for the canonical sort order; use Comparator when you need multiple or external orderings.
Common Mistakes & Pitfalls
Confusing the return value contract (negative/zero/positive) or forgetting that Comparator can be a lambda since Java 8
Check your understanding
Answer these without looking back at the article.
- What happens if compareTo is not consistent with equals in a TreeSet?
- How do you chain multiple sort criteria using Comparator?
- Can a class implement both Comparable and be used with a Comparator?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.