What is Comparator ?

Comparator is used to sort the elements in a specific order.
TreeSet and TreeMap use their default Comparator which arranges the elements in increasing order. If u want to order the elements in a different way then specify a Comparator when you construct the Set or Map.
Comapator is generic interface.
Declaration: interface Comparator
E is the type of object to be compared.
The Comparator interface defines two methods,
Compare() and equals().
public int compare(Object thisObject,Object anotherObject{
return thisObject.compareTo(anotherObject);}

The compareTo() method returns an int with the following characteristics:
■ negative If thisObject < anotherObject
■ zero If thisObject == anotherObject
■ positive If thisObject > anotherObject

No comments:

Post a Comment