Monday, June 16, 2008

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.

import java.util.Arrays;

 * @author
public class Main {
     * Creates objects using the Car class which implements the Comparable
     * interface.
     * Compares and sorts the objects by mileage.
    public void comparableExample() {
        //Creating the objects that implements the Comparable interface
        Car car1 = new Car("Toyota", 2006, 5000);
        Car car2 = new Car("BMW", 2007, 5000);
        Car car3 = new Car("Chrysler", 2007, 4000);
        //Comparing the objects by calling the compareTo method on one of them
        //passing another object as argument.
        System.out.println("Car 1 equals Car 2: " + car1.compareTo(car2));
        System.out.println("Car 1 equals Car 3: " + car1.compareTo(car3));
        System.out.println("Car 2 equals Car 3: " + car2.compareTo(car3));
        //To sort them we create an array which is passed to the Arrays.sort()
        Car[] carArray = new Car[] {car1, car2, car3};
        //Print out the sorted array
        for (Car car : carArray)
    //The Car class used to compare and sort objects.
    class Car implements Comparable {
        private String make;
        private int year;
        private int mileage;
        public Car(String make, int year, int mileage) {
            this.make = make;
            this.year = year;
            this.mileage = mileage;
        //Mandatory method when implementing the
        //Comparable interface. In this method we
        //compare the mileage of the two car objects.
        public int compareTo(Object obj) {
            if (obj instanceof Car) {
                Car car = (Car) obj;
                if (this.mileage > car.getMileage())
                    return 1;
                else if (this.mileage < car.getMileage())
                    return -1;
            return 0;
        public void setMake(String make) {
            this.make = make;
        public void setYear(int year) {
            this.year = year;
        public void setMileage(int mileage) {
            this.mileage = mileage;
        public String getMake() {
            return make;
        public int getYear() {
            return year;
        public int getMileage() {
            return mileage;
        public String toString() {
            StringBuffer buffer = new StringBuffer();
            buffer.append("Make: " + make + "\n");
            buffer.append("Year: " + year + "\n");
            buffer.append("Mileage: " + mileage + "\n");
            return buffer.toString();
     * @param args the command line arguments
    public static void main(String[] args) {
        new Main().comparableExample();

The output from the code example above is:

Car 1 equals Car 2: 0
Car 1 equals Car 3: 1
Car 2 equals Car 3: 1

Make: Chrysler
Year: 2007
Mileage: 4000

Make: Toyota
Year: 2006
Mileage: 5000

Make: BMW
Year: 2007
Mileage: 5000

Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By & Programming Blogs - BlogCatalog Blog Directory