Java · OOP, JVM and backend craft
What is the difference between Comparable and Comparator?
Short answer
Comparable defines a class's natural ordering through compareTo. Comparator defines an external ordering, so you can supply several orderings without changing the class.
Comparable is implemented by the type itself and is used by sorted collections when no comparator is supplied. Comparator is a separate object, which is preferable when ordering is context-dependent or when you cannot modify the class.
record Employee(String name, int salary) {}
Comparator<Employee> bySalary =
Comparator.comparingInt(Employee::salary).reversed();
Comparator<Employee> byName =
Comparator.comparing(Employee::name);
employees.sort(bySalary.thenComparing(byName));Rules for a correct ordering
- Be consistent with equals for sorted sets and maps, or entries can behave unexpectedly
- Return a negative number, zero or a positive number, not arbitrary values
- Use Integer.compare or Comparator.comparingInt instead of subtracting ints, which can overflow
- Handle nulls explicitly with nullsFirst or nullsLast
TreeSet and TreeMap use the ordering for equality as well as sorting. If compareTo returns zero for objects that equals considers different, the collection will drop one of them. That is a common subtle bug when sorting by only part of an object's state.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1When should you implement Comparable?
- 2How do you sort by two fields?
- 3Why is subtracting integers in compare unsafe?
- 4Why must a comparator be consistent with equals for a TreeSet?
Say it in the interview
Comparable defines the natural order inside the class through compareTo, while Comparator is an external strategy that lets me supply several orderings without changing the type. I compose comparators for multi-field sorts and use the integer comparison helper to avoid overflow. For sorted collections, the ordering must be consistent with equals, or elements can be treated as duplicates unexpectedly.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.