🔹 Introduction
Sorting objects is a common requirement in Java, and interviewers often ask:
👉 “What is the difference between Comparator and Comparable?”
🔹 What is Comparable?
Comparable is used to define natural sorting.
👉 It is implemented inside the class itself
🔹 Example (Comparable)
import java.util.*;
class Employee implements Comparable<Employee> {
int salary;
Employee(int salary) {
this.salary = salary;
}
public int compareTo(Employee e) {
return this.salary - e.salary;
}
}
public class Test {
public static void main(String[] args) {
List<Employee> list = Arrays.asList(
new Employee(50000),
new Employee(30000),
new Employee(70000)
);
Collections.sort(list);
list.forEach(e -> System.out.println(e.salary));
}
}
🔹 What is Comparator?
Comparator is used to define custom sorting.
👉 It is implemented outside the class
🔹 Example (Comparator)
import java.util.*;
class Employee {
int salary;
Employee(int salary) {
this.salary = salary;
}
}
public class Test {
public static void main(String[] args) {
List<Employee> list = Arrays.asList(
new Employee(50000),
new Employee(30000),
new Employee(70000)
);
list.sort((a, b) -> b.salary - a.salary);
list.forEach(e -> System.out.println(e.salary));
}
}
🔍 Key Differences
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo() | compare() |
| Sorting Type | Natural | Custom |
| Location | Inside class | Outside class |
🔹 When to Use What?
✔ Use Comparable
- Default sorting
- Only one logic needed
✔ Use Comparator
- Multiple sorting logic
- External control
🔹 Time Complexity
- O(n log n)
🔹 Key Takeaways
✔ Comparable → internal sorting
✔ Comparator → external/custom sorting
✔ Both are important for interviews
🔹 Conclusion
Understanding Comparator and Comparable is essential for sorting objects efficiently in Java.
Post was quite helpful for an interview...
ReplyDeleteThank you so much! Glad it helped you in your interview 😊
DeleteI’ll be posting more such questions and explanations—stay tuned!