What are the key differences between Comparable and Comparator in Java

Last updated: September 2026 — rewritten with code examples, a comparison table, and interview Q&A.

Comparable vs Comparator is a staple interview question for 2–5 year experienced candidates. The interviewer wants to hear two things: where the comparison logic lives, and how many orderings each one allows.

Comparable vs Comparator: the differences

FeatureComparableComparator
Packagejava.langjava.util
MethodcompareTo(Object o) — compares this with anothercompare(Object o1, Object o2) — compares two objects
Where it livesInside the class being sortedAny separate class
Number of orderingsOne — the "natural" orderingUnlimited — one per Comparator
Sorting typeNatural (numeric, alphabetical, chronological)Custom (by age, by date, by any field)
Can sort third-party classes?No — you can't modify their sourceYes — the logic lives outside

In code: Comparable (natural ordering)

public class Contact implements Comparable<Contact> {
    private String emailId;

    @Override
    public int compareTo(Contact o) {
        return this.emailId.compareTo(o.getEmailId());  // natural: by email
    }
}
Collections.sort(contacts);   // uses compareTo

In code: Comparator (custom ordering)

// sort orders by date, newest first — without touching the Order class
Comparator<Order> byDateDesc = (o1, o2) ->
        o2.getOrderDate().compareTo(o1.getOrderDate());
Collections.sort(orders, byDateDesc);

// need another ordering? just write another Comparator
Comparator<Order> byEmail = Comparator.comparing(Order::getEmailId);
Collections.sort(orders, byEmail);

Interview rapid-fire

  • When would you pick Comparator over Comparable? — Multiple orderings needed, or the class source isn't yours to modify.
  • What does compareTo return? — Negative if this < other, zero if equal, positive if this > other.
  • Can a class implement both? — Yes. Comparable defines the default; Comparators override per use-case.
  • Java 8+ shortcut for Comparators? — Comparator.comparing(Order::getEmailId) plus .thenComparing(...) chains.
  • What if compareTo is inconsistent with equals? — Sorted collections (TreeSet) may behave strangely — e.g., "duplicate" elimination that equals disagrees with.

Related reading

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

Java Banking Finance Services and Insurance (BFSI) domain interview questions

Java program to check even or odd number