Comparable interface in java

Any data structures in  collections framework  uses the Comparable interface  for sorting of its members . This interface is having one method compareTo().The compareTo() method returns integer value depending on the comparaison.

int status = firstObject.compareTo(secondObject)   is the general format of compareTo() method. The different possibilities of the result is explained here.

status  => Negative when firstObject < secondObject. status => 0(Zero) when firstObject == second object.

status ==Positive when firstObject > secondObject.

Now let us see an example .We have a Student.java class. It is having attributes name and id. We need to store a number of Student objects in a TreeSet  in ascending order of   attribute id .For this our Student.java needs to implement Comparable interface and the compareTo() method should have the logic to sort objects in ascending order of  id .Let us see the Student.java

Now let us see our main class to run our application. see the ComparableSample.java  shown below.

The addItems() method simply adding four Student objects into a TreeSet. First we are adding student4 object. It is having attribute id as 4. Then we are trying to add  student1 object.It is having  attribute id as 2 . So student1.compareTo(student4) will be called. Student4 is having higher value of id. So negative is returning.  Hence student1 is placing before student4. Then student2 is adding to Set. So student2.compareTo(student4) and student2.compareTo(student1) are called. Depending the return value student1 will be arranged in the Set. This comparison is continuing and a Set sorted in ascending order is getting as a result . The displayItems() method simply displays the content of the set using Iterator .

Output

In ascending order

Id = 1 ; Name = Karthik

Id = 2 ; Name = Bijoy

Id = 3 ; Name = Dexter

Id = 4 ; Name = Sasi

So our assumptions are correct.

Now what to do , to get a TreeSet in the reverse (descending)order?The answer is too simple.Just reverse the logic of compareTo() method of  Student.java.So it becomes :  return student.getId() – getId() . And verify the output !!.

One thought on “Comparable interface in java

  1. This article is a class act substance.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">