Introduction :
In Java, Comparable
& Comparator
are two interfaces used for sorting collections of objects. Both are helpful for sorting collections of objects of custom classes.
All wrapper classes by default implement Comparable, so we can directly use Collections.sort()
for lists of wrapper objects, which sorts elements in ascending order by default. However, when working with custom class objects, such as Student.java
, if we want to sort a collection of objects based on age, name, or any other property (field) of a class, we can use Comparable or Comparator. Now, let's understand Comparable and Comparator in detail.
Comparable :-
In Java, Comparable is an interface. As the name suggests, Comparable is an interface defining a strategy for comparing an object with other objects of the same type. In simple words, Comparable defines a strategy for how we want to compare one student object with another student object. This is called the class’s natural ordering.
If a class implements the Comparable interface, it means that instances of that class can be compared with each other. The Comparable interface typically has a method called compareTo()
, which is used to specify the comparison logic.
How it works: The class whose collection of objects we want to sort (in our case, a Student class) implements Comparable and overrides the
compareTo
method, which takes another object of the same type and returns:-1
if current object < other object0
if the both objects are equal1
if the current object > other object
Advantages:
Simple to implement for basic sorting based on a
single property
.No need for an extra class just for comparison.
Disadvantage:
- We can only sort objects based on single property of class.
We use Comparable when we want to sort a collection of objects based on a single property (field) of a class. For example, suppose we have a class Student.java
with fields like name, age, and rollNo. If we have a list (collection) of student objects and want to sort students based on their age, we can use Comparable. This is useful when we know that the code we have written is not going to change in the future (meaning the code will always have one sorting technique, such as age sorting, with no other sorting based on other fields).
Use Collections.sort(list)
to sort objects in ascending order and Collections.sort(list, Collections.reverseOrder())
to sort objects in reverse order.
Here is an example of Comparable:
Comparator :-
In Java, Comparator
is also an interface used for sorting collections of objects, similar to Comparable. However, Comparator offers more flexibility. With Comparator, you can create multiple custom comparators to sort a collection of objects based on different criteria.
For example, let's consider the same Student class with name, age, and rollNo fields. Using Comparator for the Student class allows you to create custom comparators like NameComparator
, AgeComparator
, and RollNoComparator
. Depending on business requirements, you can use these comparators to sort the collection of objects based on different fields.
How it works: Unlike
Comparable
, where the comparison logic is defined within the class itself,Comparator
is an external entity. You create a separate class or use a lambda expression to implement the Comparator interface and define the comparison logic in the compare method.-1
if current object < other object0
if the both objects are equal1
if the current object > other object
Advantages:
Provides flexibility to define multiple comparison strategies for the same class.
Allows sorting based on different criteria without modifying the class itself.
Well-suited for situations where the comparison logic may change or where multiple sorting strategies are required.
Disadvantage:
- Requires the creation of additional classes or implementations for different comparison strategies.
Key difference between Comparable vs Comparator
A key difference between Comparable's compareTo() method and Comparator's compare() method is that compare() takes two objects, as Comparator is designed to be a separate class where you need to pass two objects. On the other hand, compareTo() takes a single object because it compares the current object with the incoming object.
Now let's understand Comparator with examples:
We will create Student record having 2 fields
We will create separate class for Comparator prefixed by Field name and implements
Comparator<Student>
We will override
int compare(T o1, T o2);
in each custom Comparators and define comparing logic.
Conclusion:
It's generally recommended to use Comparator over Comparable when business code changes frequently. Comparator provides more advantages for sorting based on different fields. Always consider the flexibility and adaptability offered by Comparator, especially when your business logic may evolve over time.
Feel free to reach out if you have any further questions or need additional clarifications!
Follow me on Youtube : https://youtube.com/@100bitdarsh?si=v_UB8APnLLE_UP8K
Follow me on GitHub: https://github.com/sudarshan-doiphode
Reference:
Star the Repository ⭐: https://github.com/sudarshan-doiphode/Comparable-Comparator