Interview Q&A · Java · 4 questions in this topic

Comparable vs Comparator — Java Interview Q&A

All Java topics

How natural ordering with Comparable differs from custom ordering with Comparator. Part of Collections Framework · 294 questions in the Java bank.

Comparable defines the object’s own natural order, while Comparator defines an order supplied from outside. Implement Comparable when there is one obvious ordering — dates, version numbers, a domain id — and Comparator when callers need alternatives such as price, name or reverse order. A Comparator can be composed with thenComparing and reversed, and it should be consistent with equals when the object is used in sorted sets or maps. Both contracts require antisymmetry and transitivity; returning an overflow-prone subtraction breaks sorting in subtle ways.

What is the difference between Comparable and Comparator?

Answer

Comparable in java.lang defines one natural ordering through compareTo, which compares this object with another object. Comparator in java.util defines external orderings through compare, which compares two separate objects and can be supplied to sort, TreeSet, or TreeMap. A class has at most one natural ordering but can have many Comparators for alternate sort keys. Modern code often writes Comparators with lambdas or Comparator.comparing instead of anonymous classes.

Key points

  1. 1Package: java.lang versus java.util.
  2. 2Method: compareTo with one argument for self comparison versus compare with two arguments for external comparison.
  3. 3Use: implement Comparable for a default order, pass a Comparator for custom orders to sort or sorted collections.
  4. 4Count: single natural order versus unlimited custom orders.
  5. 5Consistency: keep compareTo consistent with equals, or sorted sets and maps can behave unexpectedly.
  6. 6Composition: Comparator.comparing(...).thenComparing(...) builds multi-key orders without hand-written branches.

Example

Example.javajava
Collections.sort(people);
Collections.sort(people, Comparator.comparing(Person::getAge));

💡 Name the direction: Comparable means I know how to compare myself, Comparator means a third party compares two others.

Why should compareTo be consistent with equals?

Answer

Sorted collections use comparison, not equals, to decide identity: TreeSet treats two elements as duplicates when compareTo returns 0, and TreeMap merges their keys. If compareTo returns 0 for objects that equals says are different, the collection silently drops elements. The contract asks for exactly the same equivalence: compareTo == 0 if and only if equals returns true. Comparators have the same expectation when passed to TreeMap or TreeSet.

Key points

  1. 1TreeSet.remove and TreeMap.get use comparison, not equals.
  2. 2An inconsistent compareTo silently loses distinct elements.
  3. 3compareTo == 0 should imply equals == true.
  4. 4Records and Comparable classes should document the ordering.

Why is subtracting two ints a bad compare implementation?

Answer

return a.value - b.value overflows when the values are far apart: Integer.MIN_VALUE minus a positive number wraps around and flips the sign, so the sort order becomes wrong for exactly the extreme values tests love to use. The correct form uses the comparison helpers, Integer.compare(a.value, b.value) or Comparator.comparingInt, which never overflow. The same mistake appears with longs and with hash codes.

Key points

  1. 1Subtraction overflows for large or negative differences.
  2. 2Integer.compare / Long.compare are overflow-safe.
  3. 3Comparator.comparingInt expresses intent and avoids the bug.
  4. 4The contract only needs a negative, zero or positive result.

Example

Example.javajava
// wrong — overflows
return a.value - b.value;
// right
return Integer.compare(a.value, b.value);

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits