Interview Q&A · Java · 4 questions in this topic
Comparable vs Comparator — Java Interview Q&A
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
- 1Package: java.lang versus java.util.
- 2Method: compareTo with one argument for self comparison versus compare with two arguments for external comparison.
- 3Use: implement Comparable for a default order, pass a Comparator for custom orders to sort or sorted collections.
- 4Count: single natural order versus unlimited custom orders.
- 5Consistency: keep compareTo consistent with equals, or sorted sets and maps can behave unexpectedly.
- 6Composition: Comparator.comparing(...).thenComparing(...) builds multi-key orders without hand-written branches.
Example
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
- 1TreeSet.remove and TreeMap.get use comparison, not equals.
- 2An inconsistent compareTo silently loses distinct elements.
- 3compareTo == 0 should imply equals == true.
- 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
- 1Subtraction overflows for large or negative differences.
- 2Integer.compare / Long.compare are overflow-safe.
- 3Comparator.comparingInt expresses intent and avoids the bug.
- 4The contract only needs a negative, zero or positive result.
Example
// wrong — overflows return a.value - b.value; // right return Integer.compare(a.value, b.value);
How do you sort by several fields at once?
Answer
Chain the comparators. Comparator.comparing(Person::lastName).thenComparing(Person::firstName) applies the second only when the first reports equality, and thenComparingInt or a reversed() modifier handles the rest. Build the comparator once and reuse it, since each call allocates. For a natural ordering that must live with the class, implement Comparable and let Collections.sort use it, keeping the tie-breaking rules documented.
Key points
- 1thenComparing only runs when the previous comparison returns 0.
- 2reversed() flips one key, not the whole chain, unless applied last.
- 3Reuse a stored comparator instead of rebuilding it per call.
- 4Keep the tie-break rules consistent with equals.
Example
people.sort(Comparator.comparing(Person::lastName) .thenComparing(Person::firstName) .thenComparingInt(Person::age));
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission