Name
Comparator<T>
Synopsis
This interface defines a
compare( )
method that specifies a total ordering
for a set of objects, allowing those objects to be sorted. The
Comparator
is used when the objects to be ordered
do not have a natural ordering defined by the
Comparable
interface, or when you want to order
them using something other than their natural ordering.
Comparator
has been made generic in Java 5.0 and
the type variable T
represents the type of
objects being compared.
The
compare( )
method is passed two objects. If the
first argument is less than the second argument or should be placed
before the second argument in a sorted list, compare(
)
should return a negative integer. If the first argument
is greater than the second argument or should be placed after the
second argument in a sorted list, compare( )
should return a positive integer. If the two objects are equivalent
or if their relative position in a sorted list does not matter,
compare( )
should return 0
.
Comparator
implementations may assume that both
Object
arguments are of appropriate types and cast
them as desired. If either argument is not of the expected type, the
compare( )
method throws a
ClassCastException
.
Note that the magnitude of the numbers
returned by compare( )
does not matter, only
whether they are less than, equal to, or greater than zero. In most
cases, you should implement a Comparator
so that
compare(o1,o2)
returns 0
if and
only if o1.equals(o2)
returns
true
. This is particularly important when ...
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.