Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 17: java.util Part 1: The Collections Framework 473


TheComparatorinterface defines two methods:compare( )andequals( ). Thecompare( )
method, shown here, compares two elements for order:


int compare(Tobj1, Tobj2)

obj1andobj2are the objects to be compared. This method returns zero if the objects are equal.
It returns a positive value ifobj1is greater thanobj2.Otherwise, a negative value is returned.
The method can throw aClassCastExceptionif the types of the objects are not compatible
for comparison. By overridingcompare( ), you can alter the way that objects are ordered. For
example, to sort in reverse order, you can create a comparator that reverses the outcome of
a comparison.
Theequals( )method, shown here, tests whether an object equals the invoking comparator:


boolean equals(Objectobj)

Here,objis the object to be tested for equality. The method returnstrueifobjand the invoking
object are bothComparatorobjects and use the same ordering. Otherwise, it returnsfalse.
Overridingequals( )is unnecessary, and most simple comparators will not do so.


Using a Comparator


The following is an example that demonstrates the power of a custom comparator. It
implements thecompare( )method for strings that operates in reverse of normal. Thus,
it causes a tree set to be stored in reverse order.


// Use a custom comparator.
import java.util.*;


// A reverse comparator for strings.
class MyComp implements Comparator {
public int compare(String a, String b) {
String aStr, bStr;


aStr = a;
bStr = b;

// Reverse the comparison.
return bStr.compareTo(aStr);
}

// No need to override equals.
}


class CompDemo {
public static void main(String args[]) {
// Create a tree set.
TreeSet ts = new TreeSet(new MyComp());


// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
Free download pdf