What is the difference between Comparable and Comparator?
Why Interviewers Ask This
This question targets practical, hands-on experience with Java. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
Comparable is implemented by a class to define its natural ordering. The class implements compareTo(T other), and this single ordering is used by default in sorting and sorted collections. Example: Integer, String, and Date all implement Comparable. Comparator is an external comparison strategy — a separate object that defines how two objects should be compared. It is used when you need multiple sort orders, or when you cannot modify the class. Example: Comparator.comparingInt(Person::getAge). Collections.sort and List.sort() accept a Comparator. Use Comparable for the class's primary sort key, Comparator for secondary or alternative orderings.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Java codebase.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?