Comparable vs Comparator
35 min · Intermediate
Comparable gives a class one built-in natural order through compareTo, while a Comparator is a separate object that describes any other order. Interviewers check that you know when to use each, can chain multi-field comparators, and avoid the two classic comparator bugs.
Topics in this lesson
- Natural order vs external order
- Comparator.comparing, thenComparing and reversed
- Coding question: salary descending, then name
- Traps: subtraction overflow and compareTo inconsistent with equals
Interview questions this lesson answers
- What is the difference between Comparable and Comparator?
- When would you use Comparable?
- When would you use Comparator?
- What does compareTo return?
- What is the natural order of String?
- How do you sort a list in descending order?
- How do you sort employees by salary descending and then by name?
- What does reversed() reverse in a comparator chain?
- Why is (a, b) -> a - b a bad comparator?
- What does consistent with equals mean?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.