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: 

// Inner class to sort by age then name
public static class SortByAgeName implements Comparator<Animal> {
        
}
 
  • For readability the code should be indented at the same level as methods
  • This inner class is declared to be static since it doesn't depend on any particular instance. Inner classes do not have to be static, but where they don't depend on a particular instance of the outer class then making it static means it can be instantiated without needing an instance
  • In a similar manner to the Comparable interface, Comparator can have a formal type parameter specified, i.e., <Animal>, to enforce the types of objects which are to be compared

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

// Inner class to sort by age then name
public class SortByAgeName implements Comparator<Animal> {

    @Override
    public int compare(Animal animal1, Animal animal2) {
        // comparison code will go here...
    }        
}
 

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.

// Inner class to sort by age then name
public static class SortByAgeName implements Comparator<Animal> {

    @Override
    public int compare(Animal animal1, Animal animal2) {
        // Sort by age
        int result = animal1.getAge() - animal2.getAge();
        if (result != 0) return result;

        // Sort by name
        result = animal1.getName().compareTo(animal2.getName());
        if (result != 0) return result;

        /* If reached here age and name are the same.
         * So that method is consistent with equals() will now
         * sort on hash code.
         */
        return animal1.hashCode() - animal2.hashCode();
    }
}
 

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

Arrays.sort(animalsInPen); 

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:

Arrays.sort(animalsInPen, new Animal.SortByAgeName()); 

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


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image