When working with Java Collections Framework, sorting is one of the most common operations. Java provides two powerful interfaces — Comparable and Comparator — that help developers define custom sorting logic for objects.
In this article, we’ll understand both interfaces, their differences, and when to use which one — a very popular Core Java Interview Question.
1. Comparable Interface
The Comparable interface is used to define the default natural sorting order of objects.
A class implements this interface to specify how its objects should be compared to each other.
public interface Comparable<T> {
public int compareTo(T obj);
}
2. Comparator Interface
The Comparator interface is used to define custom sorting logic outside the class.
This is useful when you want to sort objects in multiple different ways (e.g., by name, by id, etc.)
Syntax:
public interface Comparator<T> {
public int compare(T obj1, T obj2);
}
Java 8 Example using Lambda Expression
With Java 8, Comparator can be used in a more concise way:
Collections.sort(list, (s1, s2) -> s1.name.compareTo(s2.name));
When to Use Which?
-
Use Comparable when you want natural sorting (e.g., sorting students by roll number).
-
Use Comparator when you want multiple sorting criteria (e.g., sort by name, then by marks, etc.).
Conclusion
Both Comparable and Comparator are essential for sorting custom objects in Java.
-
Comparable
provides default natural order. -
Comparator
offers flexibility and customization for multiple sorting strategies.
By mastering these interfaces, you’ll be well-prepared for one of the most commonly asked Core Java interview questions.
Author:
Trilochan Tarai
Founder of java8s.com | Assistant Professor (CSE) at SoA University | Silan Software Pvt. Ltd.
No comments:
Post a Comment