← Back to Java

Comparable vs Comparator

JavaMidjava

The Question

What is the difference between the Comparable and Comparator interfaces?

What a Strong Answer Covers

  • Comparable = natural ordering in the class via compareTo
  • Comparator = external custom ordering via compare
  • Comparator allows multiple sort sequences
  • lambda for Comparator
  • java.lang vs java.util

Senior-Level Answer

`Comparable` and `Comparator` are both interfaces used for ordering objects, but they serve different design purposes.

`Comparable<T>` is implemented by a class to define its natural ordering. The single method `compareTo(T other)` returns a negative integer if `this` is less than `other`, zero if equal, and a positive integer if greater. A class implementing `Comparable` is saying: "I have a well-defined, canonical sort order." Examples: `String` (lexicographic), `Integer` (numeric), `Date` (chronological). Methods like `Collections.sort(list)` and `Arrays.sort(arr)` use natural ordering by default.

`Comparator<T>` is a separate strategy object that defines an ordering independent of the class being sorted. Its method `compare(T o1, T o2)` has the same return convention. You use a `Comparator` when you need a sort order other than the natural one, when the class you are sorting doesn't implement `Comparable`, or when you need multiple orderings for the same type.

Java 8 enriched `Comparator` with default methods: `Comparator.comparing()` creates comparators from key extractors; `thenComparing()` chains comparators for multi-level sorting; `reversed()` inverts the order. This makes complex sort logic concise: `Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName)`.

The design choice: implement `Comparable` when there is one obvious, universally applicable ordering for the type. Use `Comparator` for alternative orderings or when you cannot modify the class (e.g., sorting third-party objects).

A practical note: `TreeMap` and `TreeSet` use either the natural ordering (Comparable) or a provided Comparator. If neither is available, they throw `ClassCastException` at runtime.

Key Differences

AspectComparableComparator
Packagejava.langjava.util
MethodcompareTo(T o)compare(T o1, T o2)
Ordering typeNatural (single, built-in)Custom (multiple, external)
Modifies class?Yes — implemented by the classNo — defined separately
Java 8 extrasNonecomparing(), thenComparing(), reversed()
Use whenOne canonical sort orderAlternative/multiple orderings

What Separates a 2/3 from a 3/3

2/3 — Passing but Incomplete

Correctly contrasts natural ordering (Comparable, compareTo) with external ordering (Comparator, compare) and gives examples of each.

3/3 — Strong Answer

Also covers Java 8 Comparator factory methods, TreeMap/TreeSet behavior, and the design guidance for when to use each.

Common Mistakes

  • Getting the packages wrong — Comparable is in java.lang, Comparator is in java.util.
  • Not knowing the Java 8 Comparator.comparing() / thenComparing() API, which is now standard in real codebases.
  • Implementing Comparable inconsistently with equals() — compareTo() returning 0 should align with equals() returning true for correctness in sorted sets/maps.

Follow-Up Questions

  • What happens if you add an object to a TreeSet that doesn't implement Comparable and you provide no Comparator? — TreeSet attempts to cast the object to Comparable and throws ClassCastException at insertion time.
  • Write a Comparator that sorts a list of strings by length, then alphabetically for ties. — Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())
  • Why should compareTo() be consistent with equals() in practice? — Sorted collections like TreeSet use compareTo() to determine equality; inconsistency causes elements to be 'lost' or duplicated.

Related Questions

  • JVM vs JRE vs JDK
  • Java Platform Independence
  • How JVM Works
  • Main Features of Java
  • public static void main

Can You Explain This Cold?

Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.

Get Graded — Free Assessment
GrindQuestionsAITechnical interview assessment
TermsPrivacyAbout