The Comparator interface defines two methods: compare( ) and equals( ). The compare( )
method, shown here, compares two elements for order:
int compare(T obj1, T 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 obj1 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 compare( ), 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.
The equals( ) method, shown here, tests whether an object equals the invoking comparator:
boolean equals(Object obj)
Here, 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 equals( ) 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 the compare( ) 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<String> {
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<String> ts = new TreeSet<String>(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");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home