Tutorials

Java Collection Framework


Comparable Interface


Comparable interface is used by:

  • Collections.sort() method to sort Lists, and
  • java.util.Arrays.sort() method to sort arrays of object.

sort() method takes a List argument, and that the objects in the List must implement an interface called Comparable.

We can use it to sort the objects of:

  • String object
  • Wrapper class object
  • Custom Object*.

String and wrapper class objects implements comparable interface and thus can be directly sorted using sort() method of Collection interface.

To implement comparable, we need to implement a single method compareTo().

int res = obj1.compareTo(obj2);

 

compareTo() returns int value,

  • Negative  if obj1< obj2
  • Zero   if obj1==obj2
  • Positive   if obj1>obj2

sort() method takes a List argument, and that the objects in the List must implement an interface called Comparable.

Example: sort user defined object based on name

 

Source: Students.java

package comparable;

public class Students implements Comparable {

      int id;
      String name;

      Students(int id, String name){

            this.id = id;
            this.name = name;

      }

     //implementing compareTo
      public int compareTo(Students s){
         
            int res = name.compareTo(s.name);

            if( res==0)
                  return 0;
            if(res>0)
                  return 1;
            else return -1;

      }

      @Override
      public String toString(){

            return id +" "+ name;

      }

}

Source: test.java

 

package comparable;

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

public class test {

      public static void main(String[] args) {

            List list = new ArrayList();

            list.add(new Students(15, "Rajneesh"));
            list.add(new Students(2, "Mukesh"));
            list.add(new Students(99, "Puja"));
            list.add(new Students(67, "Simmi"));

           //sorting the user-defined object
            Collections.sort(list);

            for(Students s : list){

                  System.out.println("id="+ s.id+ " "+"name="+ s.name);

            }

      }

}

OUTPUT

id=2 name=Mukesh
id=99 name=Puja
id=15 name=Rajneesh
id=67 name=Simmi

 

 

 

 

 



Please Share this page
Views : 40