Home

compareTo

compareTo is a method used in programming to determine the relative ordering of two objects. In Java, it is defined by the Comparable interface as int compareTo(T o). The contract states that the method returns a negative integer if this object is less than the specified object, zero if they are equal, and a positive integer if this object is greater.

Implementations should define a natural order for a class. The result of compareTo is used by sorting

A key principle is that compareTo is related to equality but not identical. If compareTo returns zero,

Common implementations include lexicographic comparison for strings (based on Unicode values) and numeric comparison for wrapper

Pitfalls include violating the transitivity or antisymmetry requirements, which can break sorted collections. Null handling varies

See also: Comparable, Comparator, sort, equals.

and
ordering
operations.
For
example,
Arrays.sort
and
Collections.sort
rely
on
compareTo
to
arrange
elements,
and
data
structures
such
as
TreeSet
and
TreeMap
use
it
to
maintain
order.
many
languages
expect
that
equals
would
also
consider
the
objects
equal;
however,
this
is
not
guaranteed
unless
equals
is
implemented
consistently
with
compareTo.
Conversely,
two
objects
could
be
considered
equal
by
equals
but
not
equal
in
ordering
if
the
class
does
not
define
a
proper
natural
order.
types
like
Integer.
Many
languages
offer
a
separate
Comparator
to
define
alternate
orderings
independent
of
an
object's
natural
order.
by
language
and
may
throw
exceptions
if
the
argument
is
null.