Java Comparable Interface example


Comparable interface is  implemented by a Java class for comparing the equality or difference with other instances of this comparable class.
The comparavble class will handle comparing operation by itself.

Comparable interface structure

public interface Comparable {
public int compareTo(T o);
}

An object must implement compareTo method of Comparable interfaces like the code below;

package comparableandcomparatorexample;

/**
 *
 * @author tunatore
 */
public class Box implements Comparable<Box> {

    private long height;
    private long width;
    private long length;
    private String boxName;

    public Box(long height, long width, long length,String name) {
        this.height = height;
        this.width = width;
        this.length = length;
        this.boxName = name;

    }

    /**
     * @return the height
     */
    public long getHeight() {
        return height;
    }

    /**
     * @param height the height to set
     */
    public void setHeight(long height) {
        this.height = height;
    }

    /**
     * @return the width
     */
    public long getWidth() {
        return width;
    }

    /**
     * @param width the width to set
     */
    public void setWidth(long width) {
        this.width = width;
    }

    /**
     * @return the length
     */
    public long getLength() {
        return length;
    }

    /**
     * @param length the length to set
     */
    public void setLength(long length) {
        this.length = length;
    }

    /**
     * @return the boxName
     */
    public String getBoxName() {
        return boxName;
    }

    /**
     * @param boxName the boxName to set
     */
    public void setBoxName(String boxName) {
        this.boxName = boxName;
    }

    public int compareTo(Box boxToCompare) {
        //return zero if two objects are equal
        if (this.calculateVolume() == boxToCompare.calculateVolume()) {
            return 0;
        } //return -1 if the current object is smaller than the object compared
        else if (this.calculateVolume() < boxToCompare.calculateVolume()) {
            return -1;
        } //return 1 if the current object is bigger than the object compared
        else {
            return 1; //if (this.calculateVolume() > boxToCompare.calculateVolume())
        }
    }

    public long calculateVolume() {
        //Volume = (height.(width).(length)
        return this.height * this.width * this.length;
    }

    public String printVolume() {

        return this.boxName + “‘s volume: ” + String.valueOf(calculateVolume());
    }
}

Create a Main class for testing sorting

package comparableandcomparatorexample;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author tunatore
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

       ListboxList = new ArrayList();

       Box box1 = new Box(5,5,5,”box1″);
       Box box2 = new Box(10,10,10,”box2″);
       Box box3 = new Box(100,100,100,”box3″);
       Box box4 = new Box(2,2,2,”box4″);
       Box box5 = new Box(1,1,1,”box5″);

       boxList.add(box1);
       boxList.add(box2);
       boxList.add(box3);
       boxList.add(box4);
       boxList.add(box5);

       Collections.sort(boxList); //compareTo methods of the Box objects will be called
       //and the sorting will be done according to the return values

       for (Iterator<Box> it = boxList.iterator(); it.hasNext();) {
            Box boxCurrent = it.next();
            //sorted boxes will be printed
            System.out.println(“natural sorting:” + boxCurrent.printVolume());

        }

       Collections.sort(boxList,Collections.reverseOrder()); //compareTo methods of the Box objects will be called
       //and the reverse sorting will be done according to the return values
       System.out.print(“\n”); //new line

       for (Iterator<Box> it = boxList.iterator(); it.hasNext();) {
            Box boxCurrent = it.next();
            //sorted boxes will be printed
            System.out.println(“reverse sorting:” + boxCurrent.printVolume());

        }

    }

}

the output is;

run:
natural sorting:box5’s volume: 1
natural sorting:box4’s volume: 8
natural sorting:box1’s volume: 125
natural sorting:box2’s volume: 1000
natural sorting:box3’s volume: 1000000

reverse sorting:box3’s volume: 1000000
reverse sorting:box2’s volume: 1000
reverse sorting:box1’s volume: 125
reverse sorting:box4’s volume: 8
reverse sorting:box5’s volume: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Download Source Code

Advertisements

One thought on “Java Comparable Interface example

  1. great post just to add while using comparable interface in Java and overriding compareTo method its worth noting that compareTo must be compatible with s equals method in Java i.e. if two objects are equal via equals method compareTo method must return “0” for them, failing this may result in some subtle bug when you store those objects in collection class like TreeSet and TreeMap.

    Source: How to use Comparator and Comparable in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s