Sub topic 2
Comparable and `compareTo`
Assume you know Java classes, interfaces, generics, lists, and the equals and hashCode methods. You should also understand that a method can return a negative number, zero, or a positive number to represent a relationship.
Why a class needs a natural ordering
Sorting requires Java to answer a simple question: which of two objects comes first? Java already knows how to compare numbers and strings, but it does not automatically know how to order your own classes.
A class can define one default, or natural, ordering by implementing Comparable<T>. T is the type being compared. The interface requires this method:
int compareTo(T other)The result has meaning by its sign:
| Result | Meaning |
|---|---|
| Less than zero | This object comes before `other` |
| Zero | The objects have the same order |
| Greater than zero | This object comes after `other` |
The exact negative or positive value does not matter. Only its sign matters.
Implementing `Comparable`
Suppose a Person has a natural order based on age:
public class Person implements Comparable<Person> {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person other) {
return Integer.compare(age, other.age);
}
@Override
public String toString() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
Person younger = new Person("Bo", 25);
Person older = new Person("Ana", 31);
System.out.println(younger.compareTo(older)); // negative
System.out.println(older.compareTo(younger)); // positive
System.out.println(older.compareTo(new Person("Cy", 31))); // zero
}
}Integer.compare is safer than subtracting the ages. It returns a correctly signed result without integer overflow.
The type parameter matters. Comparable<Person> means that Person.compareTo accepts another Person. Using a raw Comparable removes useful compiler checks and should be avoided.
The `compareTo` contract
A comparison method must describe a stable ordering. If a.compareTo(b) is negative, b.compareTo(a) should be positive. If the result is zero, the two objects occupy the same position in the ordering.
The ordering should also be transitive. If a comes before b, and b comes before c, then a must come before c. A comparison that changes its answer while objects remain unchanged can make sorting and sorted collections behave unpredictably.
Java does not require compareTo to return only -1, 0, or 1. These are all valid results:
return -42;
return 0;
return 17;A common mistake is to compare one field and ignore meaningful ties. If two people have the same age, this implementation considers them equal in ordering even if their names differ. That may be correct when age is the complete natural ordering, but it must be a deliberate choice.
How natural ordering flows through Java
The relationship between a class and an operation looks like this:
Classes such as Collections and Arrays can use compareTo when no separate ordering is supplied. Sorted collections such as TreeSet and TreeMap can also use it. Later, you will see how a Comparator supplies an alternative ordering without changing the class.
Exercise
What should compareTo return when this object belongs before the argument, and why should you use Integer.compare instead of subtracting integer fields?
Show answer
It should return a negative value. Integer.compare avoids overflow, which can make subtraction produce the wrong sign for large or negative integers.