Comparator Interface
Home ] Up ] Comparable Interface ] [ Comparator Interface ] Collections Class ] Comparable Example ] Comparator Example ] General Applicability ]

 

 

The Comparator interface is for imposing an ordering in the case where you might wish to compare two objects that do not implement the Comparable interface (or even on objects that do, if you wish).

Collection
    List
    Set
        SortedSet
Comparable (in java.lang package)
Comparator
Enumeration
Iterator
    ListIterator
Map
    SortedMap

Comparator defines the following methods:

package java.util;

public interface Comparator 
{
    int compare(Object o1, Object o2);
    boolean equals(Object obj);
}

As with the Comparable compareTo method, the Comparator compare method returns:

  • a negative integer if the first argument is less than the second argument
  • zero if the first argument is equal to the second argument
  • a positive integer if the first argument is greater than the second argument

The equals method may or may not need to be implemented in the class that implements Comparator, because the Object class implements such an equals method, which suffices for most purposes.  However, you may wish to override this method to improve performance by allowing programs to determine that two distinct Comparators impose the same order.

 

This page was last modified on 02 October, 2007