The contract for the compareTo(Object obj)
method demands that you return:
- n < 0 if
this
is to be considered less than obj
- 0 if
this
is equal to obj
- n > 0 if
this
is greater than obj
This way you can define sorting behavior for your class.
Arrays.sort(people);
Note that you can sort your objects backwards by just inverting the sign of the return value.
As a side note, some sorting methods allow you to pass a Comparator
along with the collection you want to sort, which enables you to define a different sort criterion other than the default one.
Arrays.sort(people, new Comparator<Person>() { ... });