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)
public class Person implements Comparable<Person> {
public int compareTo(Person other) {
int c = this.name.compareTo(other.name);
return Integer.compare(this.age, other.age);
}
}
Alternatives include using Comparator to define alternate orders. See also Comparable, Comparator, and Ordering.