Comparable interface in Java

For more information please go through http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

This interface imposes a natural ordering on objects of each class that implements it and the class’s compareTo method is referred to as its natural comparison method.

Lists or arrays of objects that implement this interface can be sorted automatically by Collections.sort or Arrays.sort respectively. Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set.

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave “strangely” when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.

The class which implements Comparable interface must override the below method

int compareTo(T o)

o – the object to be compared.

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

We will now see how we can use Comparable interface in the following example

Prerequisites

The following things are required in order to run the application

Eclipse Helios
JDK 1.6 or higher

Step 1. Create the below POJO class which implements Comparable interface

Step 2. Create a test class with below source code

Step 3. Run above class and you will get the below output

That’s all. Thank you for reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.