4 min read
Comparable & Comparator
Prerequisites: The collections framework
Comparable gives a class one natural ordering; Comparator
defines any number of external, situational orderings without
changing the class itself.
class Person implements Comparable<Person> {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age);
}
}
List<Person> people = new ArrayList<>();
people.add(new Person("Ada", 36));
people.add(new Person("Grace", 85));
Collections.sort(people); // uses compareTo — sorts by age
people.sort(Comparator.comparing(p -> p.name)); // sorts by name instead
Common mistakes
- Implementing
compareToinconsistently withequals(e.g. two objects compare as "equal" viacompareTobut.equals()says they're different) — this can produce surprising results in sorted collections likeTreeSet.