☕ Java
Intermediate
What is the difference between Comparable and Comparator?
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.
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?