Sub topic 4
Giving Your Class a Natural Ordering
Assume you know Java classes, interfaces, generics, lists, and the Collections framework. You should also understand equals and hashCode. This chapter uses Java 7 syntax and APIs.
Why define a natural ordering?
A natural ordering is the default order for objects of a class. For example, Person objects might naturally be ordered by age. Once the class defines this order, sorting code can use the objects without receiving a separate comparison rule.
Java represents a natural ordering with the Comparable<T> interface:
public interface Comparable<T> {
int compareTo(T other);
}The method result has meaning rather than a required exact value:
| Result | Meaning |
|---|---|
| Negative | This object comes before `other` |
| Zero | The objects are equal in the ordering |
| Positive | This object comes after `other` |
Implementing `Comparable`
The class declares implements Comparable<Person> and defines compareTo(Person).
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NaturalOrderDemo {
public static final 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) {
List<Person> people = new ArrayList<Person>();
people.add(new Person("Ana", 31));
people.add(new Person("Bo", 25));
people.add(new Person("Cy", 31));
Collections.sort(people);
System.out.println(people);
}
}The output is:
[Bo (25), Ana (31), Cy (31)]Collections.sort finds the natural ordering because Person implements Comparable<Person>. The sort is stable, so Ana remains before Cy because they have equal ages and Ana originally appeared first.
The comparison uses Integer.compare instead of subtracting the ages. A comparison must report the correct sign. Subtraction can overflow when values are near the limits of the int type.
The `compareTo` contract
A correct implementation follows these rules:
x.compareTo(y)is negative, zero, or positive according to the order.- If
x.compareTo(y)is zero, reversing the operands must also produce zero. - Reversing two non-equal objects reverses the sign: if
xcomes beforey, thenycomes afterx. - Comparisons should be transitive. If
acomes beforeb, andbcomes beforec, thenashould come beforec.
The method should also handle null deliberately. Most implementations naturally throw NullPointerException when the other object is null. That is usually preferable to inventing an order for a missing object.
flowchart TD
A[Person objects] --> B[Collections.sort]
B --> C[Calls compareTo]
C --> D[Compares ages]
D --> E[Negative, zero, or positive result]
E --> F[Sorted list]Ordering and equality
Returning zero from compareTo means the objects are equal for ordering purposes. This does not automatically mean that equals returns true, but keeping the two definitions consistent is usually safer.
For this example, two people with the same age compare as equal even if their names differ. That is acceptable only if age is truly the intended ordering identity. Sorted collections such as TreeSet may keep only one of those two objects because they use comparison results to detect duplicates.
Exercise
What does compareTo need to return when this object should appear after the argument, and why should you use Integer.compare instead of subtracting two ages?
Show answer
It should return a positive value. Integer.compare avoids integer overflow, which can make subtraction produce the wrong sign.