Overview | Package | Class | Tree | Index | Help
PREV CLASS | NEXT CLASS FRAMES  | NO FRAMES
SUMMARY:  INNER | FIELD | CONSTR | METHOD DETAIL:  FIELD | CONSTR | METHOD

Interface java.util.Comparator


public abstract interface Comparator
A comparison function, which imposes a partial or total ordering on some collection of Objects. Comparators can be passed to a sort method (such as Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap).

A Comparator c imposes a total ordering on a set of elements S if and only if c.compare(e1, e2)==0 implies that (e1.equals(e2) || (e1==null e2==null)) for every e1 and e2 in S. This is mentioned here because some applications that call for a comparator will require that the comparator impose a total ordering (such as SortedMap and SortedSet).

Note: It is generally a good idea for Comparators to implement java.io.Serializable, as they may be used as ordering methods in Serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the Comparator (if provided) must be Serializable.

Since:
JDK1.2
Version:
1.8 06/29/98
See Also:
java.lang.Comparable, sort(Object[], Comparator), TreeMap, TreeSet, SortedMap, SortedSet

Method Summary
int compare(java.lang.Object o1, java.lang.Object o2)
          Compares its two arguments for order.
 

Method Detail

compare

public int compare(java.lang.Object o1,
                   java.lang.Object o2)
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

The implementer must also ensure that x.equals(y)||(x==null && y==null) implies that compare(x, y) == 0. Note that the converse is not necessarily true. If the converse is false, this Comparator induces a partial (not total) ordering.

Finally, the implementer must ensure that compare(x, y) == 0 implies that sgn(compare(x, z)) == sgn(compare(y, z)), for all z.

Returns:
a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Throws:
ClassCastException - the arguments' types prevent them from being compared by this Comparator.


Overview | Package | Class | Tree | Index | Help
PREV CLASS | NEXT CLASS FRAMES  | NO FRAMES
SUMMARY:  INNER | FIELD | CONSTR | METHOD DETAIL:  FIELD | CONSTR | METHOD