☕ 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.