Skip to main content

What is the difference between Comparable and Comparator?

Junior Java
Quick Answer Comparable: implemented by the class itself (implements Comparable), defines "natural ordering" via compareTo(). Used by sort() and sorted collections automatically. Comparator: external comparison logic - doesn't modify the class. Pass to sort(), TreeMap, sorted collections. Comparator is more flexible - create multiple comparison strategies. Java 8: Comparator.comparing(Person::getAge).thenComparing(Person::getName).

Answer

Comparable: Natural ordering defined in class.
Comparator: External custom sorting logic.
Both used during sorting.
S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice