Explanation
You have to define this order by implementing the compareTo
method that is forced on you when implementing Comparable
.
This order should be what a human would call natural for this type. So for example ascending by value for integers (1, 2, 5, 9
), maybe by age for Person
s. It is your choice as designer to choose something that users would find natural and not confusing for your custom classes.
It will then be used as default ordering if you, for example sort a collection of this type.
See the documentation of Comparable and its Comparable#compareTo method:
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo
method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort
(and Arrays.sort
). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.
Example
Here is a small example:
public class Person implements Comparable<Person> {
private final String name;
private final int age;
// Constructor, getters, ...
@Override
public int compareTo(Person other) {
// Compare based on age, ascending
return Integer.compareTo(age, other.age);
}
}
With a usage like:
Person first = new Person("John", 20);
Person second = new Person("Jane", 18);
Person third = new Person("Bob", 30);
List<Person> persons = new ArrayList<>();
persons.add(first);
persons.add(second);
persons.add(third);
// Ordering is now: John, Jane, Bob
// Sort based on natural ordering
Collections.sort(persons);
// Ordering is now: Jane, John, Bob