Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Comparator interface is used to order the objects of user-defined class. This interface is present java.util package and contains 2 methods
- int compare(T o1, T o2)
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.equals(Object element). - boolean equals(Object obj)
Indicates whether some other object is “equal to” this comparator.
int compare(Object obj1, Object obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj2 is greater than obj1. Otherwise, a negative value is returned.
By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.
boolean equals(Object obj)
obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.