Member-only story
Comparable vs Comparator in easy way 🤓
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…