By Tony Bevis on Wednesday, 11 October 2023
Category: Java

Java programming course: 6.5 Sorting in alternative sequences

In the previous lesson you saw how to sort arrays and objects in their "natural" sequence.

Sorting in alternative sequences

You have seen that making your class implement the Comparable interface and implementing its compareTo() method lets you define a class's natural (or default) ordering. But what if in addition to this you need an alternative sorting order for a particular purpose?

To define alternative sorting criteria, you can create a class which implements a related interface called Comparator. This interface specifies a compare() method which provides two arguments, being two objects to sort. While you could create a complete new class to implement Comparator there is a facility in Java to define inner classes, these being a class which exists inside another class. You would use an inner class when its purpose is directly related in some way such that it is logically part of the same class within which you define it.

Therefore, inside the Animal class, where you would otherwise define a new method, include the following code: 


The Comparator interface requires you to implement the compare() method, which has the following signature:

You can now enter the following statements to sort firstly by age and then by name. If both are the same, the hash codes are then compared for the same reason as in the compareTo() method.

You will recall that within Experiments you specified the following statement to sort an array based on its natural ordering:

The sort() method in the Arrays class is overloaded, and can accept a second argument that specifies a Comparator object on which to base the sort criteria. Change the above statement as follows:

Above, the inner class SortByAgeName of the Animal class is instantiated to provide the Comparator object that the sort() method will use.

In the next series of lessons we will cover handling exceptions.

Next lesson: 7.1 Exceptions

Related Posts

Leave Comments