SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 6 / 25

Junior

What is the difference between Comparable and Comparator, and when do you use each?

Short answer

Comparable is the natural order written inside the class, one per class. Comparator is a way to compare outside the class, as many as you like.

inside, only oneoutside, manyrecord EmployeeComparablecompareTo by nameComparatorcomparecomparing(Employee::dept)thenComparing salarydescending

3 points to say:

  1. Comparable: one single order, edited inside the class.
  2. Comparator: many orderings, works for any class.
  3. Only the sign of the result matters: negative, 0, positive.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.