Home

Comparativeto

Comparativeto, usually written as compareTo, refers to a method used in programming to establish a natural ordering among objects of a class. It defines how one instance compares to another by returning a negative integer if the first is less than the second, zero if they are considered equal in ordering, and a positive integer if the first is greater.

In many languages the method is part of a comparable interface. In Java, the interface Comparable<T> requires

Semantics and contract: a compareTo implementation should be antisymmetric and transitive. If a.compareTo(b) < 0 and b.compareTo(a)

Example (Java):

public class Person implements Comparable<Person> {

private String name;

private int age;

public int compareTo(Person other) {

int c = this.name.compareTo(other.name);

if (c != 0) return c;

return Integer.compare(this.age, other.age);

}

}

Alternatives include using Comparator to define alternate orders. See also Comparable, Comparator, and Ordering.

int
compareTo(T
o);
objects
implementing
it
can
be
sorted
with
their
natural
order
using
utilities
like
Arrays.sort
or
Collections.sort.
In
C#,
the
pattern
appears
as
IComparable
or
IComparable<T>,
with
int
CompareTo(T
other).
Other
languages
may
use
different
naming
or
three-way
comparison
operators,
but
the
core
idea
remains:
a
single
method
expresses
total
ordering.
<
0,
ordering
is
inconsistent.
A
common
expectation
is
that
if
a.compareTo(b)
==
0,
then
a
and
b
are
considered
equal
in
ordering;
this
often
but
not
always
aligns
with
equals.
Implementations
should
be
careful
with
null
handling,
as
languages
differ
on
whether
null
is
allowed
to
be
compared.