Java Comparable and Comparator – Complete Guide with Examples
Learn how to sort objects in Java using Comparable and Comparator interfaces, their differences, methods, and practical examples for custom sorting of collections.
Comparable and Comparator in Java – Complete Detailed Tutorial
In Java, sorting objects requires defining order. The Comparable and Comparator interfaces provide ways to define natural and custom ordering for objects.
1. Comparable Interface
- Defines natural ordering for objects
- Part of java.lang package
- Used with Collections.sort() or Arrays.sort()
- Implements
compareTo()method
Syntax:
- Returns negative → current object < obj
- Returns zero → current object == obj
- Returns positive → current object > obj
Example – Using Comparable
Output:
Key Points:
- Comparable is implemented by the class itself
- Defines natural ordering
- Only one sorting sequence possible
2. Comparator Interface
- Defines custom ordering for objects
- Part of java.util package
- Can be separate class or anonymous class
- Implements
compare()method
Syntax:
- Returns negative → o1 < o2
- Returns zero → o1 == o2
- Returns positive → o1 > o2
Example – Using Comparator
Output:
Key Points:
- Comparator is a separate class
- Can define multiple sorting sequences
- Useful when class cannot implement Comparable
3. Comparable vs Comparator
| FeatureComparableComparator | ||
| Location | Implemented by class itself | Separate class or lambda |
| Method | compareTo() | compare() |
| Multiple sort sequences | No | Yes |
| Package | java.lang | java.util |
| Sorting | Natural order | Custom order |
4. Key Points
- Use Comparable for default/natural sorting
- Use Comparator for custom or multiple sort criteria
- Works with Collections.sort(), Arrays.sort()
5. Summary
- Comparable: class defines its own natural ordering
- Comparator: external class defines custom ordering
- Both are essential for sorting Java objects efficiently