Sub topic 1
Why Java Needs a Definition of Order
When a program stores numbers, order is clear: 2 comes before 5. Objects are different. A Person has a name, age, and perhaps an employee ID. Which person comes first?
Java needs an ordering rule whenever code must arrange objects, choose the smallest object, or decide which object has priority. The rule must answer whether one object is less than, equal to, or greater than another.
Prerequisites
You should know Java classes, interfaces, generics, lists, and the basic Collections Framework. You should also understand that equals compares objects for logical equality.
One object can have several useful orders
Consider these people:
| Person | Age | Name |
|---|---|---|
| Ana | 31 | Ana |
| Bo | 25 | Bo |
| Cy | 31 | Cy |
A directory might order them by name. A queue for an age-based study might order them by age. A payroll report might order them by employee ID.
None of these rules is automatically the correct rule. Java cannot infer your program's meaning from the fields in a class. You must provide an ordering when the operation needs one.
An ordering lets Java perform tasks such as:
- sorting a list;
- finding the earliest date or lowest price;
- keeping a
TreeSetin sorted order; - choosing the next item from a
PriorityQueue; - finding a key in a sorted map or array.
Without a definition of order, a sorting method has no reliable way to compare two objects.
What a comparison must communicate
A comparison does not need to return exactly -1, 0, or 1. It needs to return a sign:
- a negative value if the first object comes before the second;
- zero if the objects are equivalent for this ordering;
- a positive value if the first object comes after the second.
For example, comparing Ana and Bo by age says that Ana comes after Bo because 31 is greater than 25. Comparing Ana and Cy by age says they are tied because both are 31.
The ordering must be consistent. If Ana comes before Bo, and Bo comes before Cy, the rule must also say that Ana comes before Cy. A sorting algorithm depends on this consistency. A rule that gives contradictory answers can produce confusing results or fail inside sorted collections.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
static class Person {
final String name;
final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Ana", 31));
people.add(new Person("Bo", 25));
people.add(new Person("Cy", 31));
Comparator<Person> byAge =
(first, second) -> Integer.compare(first.age, second.age);
people.sort(byAge);
System.out.println(people);
}
}The comparator in this example defines one particular ordering. It does not change the Person class. Later, a different comparator can order the same objects by name.
Where the rule can live
Java provides two main designs:
Comparablegives a class one natural ordering. The class defines how its instances compare by default.Comparatorgives an ordering from outside the class. Different parts of a program can use different rules for the same objects.
For example, a Person class might naturally order people by an employee ID, while a screen orders them by name and a report orders them by age. Choosing between these designs depends on whether one ordering is fundamental to the type or whether callers need several alternatives.
The next sections examine the contracts behind these rules and the Java interfaces that represent them.
Exercise
Why can Java not automatically choose the correct order for a Person object?
Show answer
A Person can be meaningfully ordered by several fields, such as name, age, or employee ID. The program must choose the rule that matches its operation.