Doth TreeSet and TreeMap store elements in sorted order. However, it is the. comparator that defines precisely what "sorted order" means. By default, these classes store their elements by using what Java refers to as "natural ordering," which is usually the ordering that you would expect. (A beforeB, Ibefore 2, and so forth.j If you want to order elements a different way, then spcl:ify'a Comparator object when you construct the set or map. Doing so gives you the ability to govern precisely how clements arc stored within sorted collections and maps. The Comparator interface defines two methods: compare() and equals(). The comparee ) method, shown here, compares two elements for order: , int compare(Object objl, Object obj2)

objl and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns ,a positive value if objl is greater than obj2. Otherwise, a negative value is returned. The method can throw a ClassCastException if the types of the objects are not compatible for comparison. By overriding comparet ), you can alter the way that' objects are ordered. For example, to sort in reverse order, you can create a comparato~ that reverses the outcome of a comparison. The equalsl ) method, shown here, tests whether an object equals the invoking comparator: ' '

boolean eCJ,uals(Objectobj)

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. Overriding equalsl ) is Ulwecessary, and most simple comparators will so,

Share This