Summary:

In this post, we will explore how to use the Java comparable interface to automatically sort collections of any classes. We will use the Java Collections from the util library as an example.

 

Introduction:

Java interfaces are one of the most powerful features of the object oriented programming language. When a class implements an interface, it behaves as a programming contract that is guaranteed to be fulfilled. In other words, if a class implements an interface, then we can rely that certain functionality is available with instances of this class, and every other class that implements that interface.

 

We will explore interfaces in more detail in a later post. For now, let us take the Collections utility from Java as an example. The sort method accepts a list as an argument. If the list elements implement the comparable interface, then we have automatically achieved compatibility with the “sort” functionality. Below is the class Car, which has three members. The car brand, the car model and the maximum speed.

 

For the sake of simplicity, we will use just the maximum speed for comparison. The requirement for the comparable interface is only one method, the “compareTo” method. When comparing instance A to B, the following output is expected:

  • If A is more than B, then return a positive number
  • If is less than B, then return a negative number
  • If A and B are considered equal, then return zero.

 

Below is an example implementation of the comparable interface.

 

Now, let us put the theory to the test. Below is a test that initializes four different instances of the Car class and we will attempt to sort them using the Collections util from Java.

 

 

The following output was obtained from the log statements:

 

 

Notice that the first log statement printed the cars with the order they were at in the original list. The second list had the cars sorted by their maximum speed. We didn’t need to implement any sorting algorithm. We only needed to define which car is “more than” the other one, and then we took advantage of the built in Java functionality to sort the list 😉