wellnwill Marathahalli Bangalore

To sort data with Comparable

Comparable interface:

This interface is present in java.lang package and contains only one method i.e. compareTo().

public int compareTo() method: This method compares two objects.

compareTo() returns three values:

if object1 < object2 => return negative number
if object1 == object2 => return zero  
ex-obj1.compareTo(obj2);

We can perform sorting for String object, Wrapper class object and user defined object with compareTo()

import java.util.Arrays;
class B implements Comparable
{
int i;

 B(int i)
 {
  this.i=i;
 }
 
 public String toString()
 {
	 return i+"";
 }
 
 public int compareTo(Object o)
 {
  B a=(B)o;
  if(this.i==a.i)  
     return 0;  
  else if(this.i>a.i)  
     return 1;  
  else  
     return -1;
 }
}


class Test274
{
 public static void main(String args[])
 {
  B a[]=new B[3];
  a[0]=new B(9);
  a[1]=new B(3);
  a[2]=new B(5);
  
  for(B a1:a)
  {
   System.out.println(a1);
  }
  System.out.println("..........");
  Arrays.sort(a);
   for(B a2:a)
  {
   System.out.println(a2);
}
}
}




import java.util.Arrays;

class Person implements Comparable
{
 int id;
 String name;
 int sal;
 
 Person(int id,String name,int sal)
 {
  this.id=id;
  this.name=name;
  this.sal=sal;
 }
 
 public String toString()
 {
  return id+".."+name+".."+sal;
 }
 //comparision based on sal
public int compareTo(Object o)
 {
  Person p=(Person)o;
  if(this.sal==p.sal)  
     return 0;  
  else if(this.sal>p.sal)  
     return 1;  
  else  
     return -1;
 }
}
public class Test276
{
 public static void main(String args[])
 {
 Person p[]=new Person[4];
 p[0]=new Person(4,"John",20000);
 p[1]=new Person(2,"David",26000);
 p[2]=new Person(3,"Mac",22000);
 p[3]=new Person(1,"Robert",21000);
 
 for(Person p1:p)
 {
 System.out.println(p1);
 }
 System.out.println("........");
 Arrays.sort(p);
 for(Person p1:p)
 {
 System.out.println(p1);
 }
 }
} 
Footer with Map

Top