Using the Comparable interface to compare and sort objects

This code example shows how to compare and sort objects by implementing the Comparable interface. The code consists of a class called Main and another class called Car.
The Main class creates a few instances of the Car class (which is the one that implements the Comparable interface) and them compare them and also sort them.

The Car class has three attributes, make, year and mileage. Only the mileage attribute is really of importance here since it’s the attribute used for comparing.
When a class implements the Comparable interface it has to implement a method called compareTo(). In that method the code has to be written to decide if two objects match or if one is larger than the other.

In the example we return 1 if the current car object (the one we’re calling compareTo() on) has a greater mileage value than the object passed in as parameter, -1 if it’s the other way around and if they’re equal 0 is returned.
The toString() method is overridden so a car object can be printed out in a readable way. Finally we create an array of cars and pass it to the sort() method of the Arrays class and then print out the sorted array.

The output from the code example above is:

Search for more Java info on this site here:
Custom Search

Please type any questions here.