As discussed in my previous blog, we got a brief idea about java.lang.Comparable Interface which is used to sort the elements in a natural ordering. Now in this tutorial, we will learn something new which is comparator interface.
This interface is defined under java.util package so that's why this is sometimes called as a utility interface which should be used as a utility for sorting the objects.
--> Comparator interface in java has a method known as public int compare(Object 1,Object 2) which returns a negative integer, zero or positive integer as obejct 1 is less than, equal to or greater than object 2.
Why Comparator?
Now the question comes , why we want comparator interface when we want to sort the objects by primary key attribute we can do it by comparable Interface. den what is the need of Comparator Interface? And the answer lies here:-