When would you use Comparator instead of Comparable?
Options
Comparableis for sorting;Comparatoris for hashingComparableis the natural order;Comparatoris external (Correct option)- They are identical, only the name of the method changes
Comparatoronly works on numbers and never on objects
Answer
Comparable defines the natural order inside the class; Comparator defines extra or external orderings without changing the class
Why
Comparable<T> is implemented by the class itself with compareTo. It defines ONE natural order (e.g. String alphabetical, Integer numeric).
Comparator<T> is a separate object with compare(a, b). You can have many: by name, by age, by date. It is also the only choice when you cannot modify the class.
Modern style: people.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName)).
Remember
Comparable = natural order inside. Comparator = custom orders outside.