Repaso
EspaƱol
Java CoreIntermediateJV-28

When would you use Comparator instead of Comparable?

Options

  1. Comparable is for sorting; Comparator is for hashing
  2. Comparable is the natural order; Comparator is external (Correct option)
  3. They are identical, only the name of the method changes
  4. Comparator only 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.

Key terms

Practice this question in Repaso