Return to site

What’s the difference between Comparable and Comparator in Java?

· java,interview,video

🚀 Java Interview Questions – Episode 8
💡 What’s the difference between Comparable and Comparator in Java?

🧩 Both are used to sort objects, but they serve different purposes:

📌 Comparable
➡️ Interface used to define the natural ordering of objects.
➡️ You implement it in the class itself by overriding the compareTo() method.
🔸 Example: String, Integer classes implement Comparable.

📌 Comparator
➡️ Allows you to define custom orderings, outside the class.
➡️ Useful when you want multiple sorting strategies.
🔸 Example: Sort Employee by name or by salary using different comparators.

🧠 Summary:
Comparable = self-sorting (inside the class)
Comparator = external sorting logic