Comparator is almost same as Comparable with mild difference.
Since, in case of Comparable we had to put an extra method 'compareTo()' in the Bean (i.e. Human). Which was quite unlikely.
To overcome this restriction Comparator came into picture where we can create a different class/classes where the sorting logic will be present.
Sounds tough, no worries, we will explain in detail.
So, in case of Comparator, we won't be making any change to the bean (i.e. The Human class). Rather, we would be writing the sorting logic in a seperate class.
So, we have created a different class AgeSort which did implement Comparator and override compare() method.
The Comparator uses 'int compare(Object o1,Object o2)' instead of 'int compareTo(Object o)'.
The 'int compare(Object o1, Object o2)' method accepts two Objects as Parameter. Again with Generics(class AgeSort implements Comparator <Human> ), we were able to put two Human objects (i.e. Human h1 and Human h2).
And just like compareTo() this method is also retuning the subtracted value of the ages of h1 and h2.
Now, let us define the class with main() method.
For Comparator we need to use :
The first parameter is the List to be sorted(i.e. listName) and the second parameter (i.e. new AgeClass()) is the class where the sorting logic is defined.
Pretty simple, right.
1. We have created a new class NameSort which implemented Comparator.
2. Inside the compare() method we have made two variables name1(Contains the name of h1 object) and name2(Contains the name of h2 object).
3. In the return statement we have called the compareTo() by 'name1' by passing 'name2' as parameter.
As we know compareTo() is a method of String. So, the substraction of two Strings will be taken care by the String class and the '-ve', '+ve' or '0' value will be returned to Collections.sort(listHuman,new NameSort()). On the basis of which sorting will be done.