Sorting custom objects

One of the more frequently encountered cases is the need to sort custom objects, such as Car, or Person type, for example. To do it, there are two options:

  • Implement the Comparable interface. It has only one method, compareTo(T), which accepts an object of the same type and returns a negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the specified object. Such an implementation is called a natural ordering because objects that implement the Comparable interface can be ordered by the method sort() of a collection. Many of the examples of the previous subsection demonstrated how it works for the objects of type String. Comparators are returned by the methods naturalOrder() ...

Get Introduction to Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.