Sub topic 1
Why Java Needs a Definition of Order
Prerequisites
You should know Java classes, interfaces, generics, lists, and the equals and hashCode methods. You should also understand that an interface defines methods a class agrees to provide.
Why Java Needs a Definition of Order
Sorting requires Java to answer a basic question: should object a come before object b? Numbers and strings already have an obvious order. A custom Person object does not. Should people be ordered by age, name, or employee number?
Java separates the objects from the rule that orders them. Comparable puts one default, or natural, ordering inside the class. Comparator supplies another ordering outside the class. This chapter focuses on the natural ordering.
flowchart LR
A[Objects] --> B[Comparison rule]
B --> C[Negative: first comes before second]
B --> D[Zero: equal in ordering]
B --> E[Positive: first comes after second]Comparable and compareTo
Comparable<T> is a generic interface for objects that have a natural ordering. A class implements it and defines compareTo(T other).
The method returns:
- A negative number when this object comes before
other. - Zero when both objects have the same position in the ordering.
- A positive number when this object comes after
other.
The exact nonzero number does not matter. Only its sign matters.
The Rules a Comparison Must Follow
A comparison must describe one coherent ordering:
- The sign of
compareTo(a, b)should be the opposite ofcompareTo(b, a). - If
acomes beforebandbcomes beforec, thenashould come beforec. - If
compareTo(a, b)returns zero, both objects occupy the same position for this ordering.
Ideally, returning zero should also agree with equals. If it does not, sorted collections such as TreeSet can treat distinct objects as duplicates.
Giving Your Class a Natural Ordering
This class orders people by age:
public 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;
}
@Override
public int compareTo(Person other) {
return Integer.compare(this.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) < 0); // true
}
}Integer.compare avoids arithmetic overflow and clearly expresses the intended comparison.
Exercise
What should compareTo return when two objects have the same ordering position?
Show answer
It should return zero.