Java - Comparable and Comparator Interface-interview
Q1. What is the difference between Comparable and Comparator in Java?
- Comparable provides a single natural ordering via compareTo().
- Comparator provides custom ordering via compare().
- Comparable is implemented in the class itself, whereas Comparator is implemented in a separate class.
Q2. Can a class implement both Comparable and Comparator?
Yes, a class can implement both. Comparable can define the natural ordering, while separate Comparator implementations can provide different custom orderings.
Q3. Which method is used in Comparable and Comparator?
- Comparable → compareTo(Object o)
- Comparator → compare(Object o1, Object o2)
Q4. In which package are Comparable and Comparator present?
- Comparable → java.lang package
- Comparator → java.util package
Q5. When would you prefer Comparator over Comparable?
Use Comparator when you need multiple sorting logics (e.g., sorting employees by name, age, or salary). Comparable is suitable when only one natural order is required.