In Java, sorting is an important operation when working with collections such as ArrayList, LinkedList, and other data structures. For primitive data types, Java already knows how to sort values. However, for custom objects like Student, Employee, or Product, Java needs instructions on how objects should be compared.
To achieve this, Java provides two interfaces:
- Comparable β Used for natural sorting.
- Comparator β Used for custom sorting.
Comparable Interface
Comparable is an interface available in the java.lang package.
It is used to define the natural ordering of objects. The sorting logic is written inside the class itself using the compareTo() method.
Method
int compareTo(T obj)
Return Values
- Negative - Current object comes before the given object
- Zero - Both objects are equal
- Positive - Current object comes after the given object
When to Use Comparable?
Use Comparable when:
- A class has one default sorting order.
- The sorting logic is a natural property of the object.
- The sorting criteria rarely change.
Comparator Interface
Comparator is an interface available in the java.util package.
It is used to define custom sorting logic outside the class. Multiple comparators can be created for the same class.
Method
int compare(T o1, T o2)
Return Values
- Negative - First object comes before second object
- Zero - Both objects are equal
- Positive - First object comes after second object
When to Use Comparator?
Use Comparator when:
- Multiple sorting criteria are required.
- You don't want to modify the original class.
- Different sorting orders are needed at different times.
Top comments (0)