Name
Comparable<T>
Synopsis
This interface defines a single
method, compareTo( )
, that is responsible for
comparing one object to another and determining their relative order,
according to some natural ordering for that class of objects. Any
general-purpose class that represents a value that can be sorted or
ordered should implement this interface. Any class that does
implement this interface can make use of various powerful methods
such as java.util.Collections.sort( )
and
java.util.Arrays.binarySearch( )
. Many of the key
classes in the Java API implement this interface. In Java 5.0, this
interface has been made generic. The type variable
T
represents the type of the object that
is passed to the compareTo( )
method.
The compareTo( )
method compares this object to
the object passed as an argument. It should assume that the supplied
object is of the appropriate type; if it is not, it should throw a
ClassCastException
. If this object is less than
the supplied object or should appear before the supplied object in a
sorted list, compareTo( )
should return a negative
number. If this object is greater than the supplied object or should
come after the supplied object in a sorted list, compareTo(
)
should return a positive integer. If the two objects are
equivalent, and their relative order in a sorted list does not
matter, compareTo( )
should return 0. If
compareTo( )
returns 0 for two objects, the
equals( )
method should typically return
true
. If this is not the case, the
Comparable
objects ...
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.