Thursday 22 November 2012

Introduction with comperator and comperable

Introduction with comperator and comperable:

Comperator and comperable are interfaces used for compairing objects .

Implementation of Comparator and Comperable Interfaces

class Student implements Comparator<Student>{
   private String name;
   private int age;
   Student(){   }

   Student(String stdName, int stdAge){
      name = stdName;
      age = stdAge;
   }

   public String getName(){
      return name;
   }

   public int getAge(){
      return age;
   }

   
   // Overriding the compare method to sort the age 
   public int compare(Student s1, Student s2){
      return s1.age - s2.age;
   }
}
 
public class Member implements comperable<Member>{
   private String name;
   private int age;
    Member(){
   }

   Student(String memName, int mebAge){
      name = mebName;
      age = mebAge;
   } 

 
 
 // Overriding the compareTo method
   public int compareTo(Member mem){
      return (this.name).compareTo(mem.name);
   }
}
 public class MainClass{
   public static void main(String args[]){
     
      List<Student> list = new ArrayList<Student>();

      list.add(new Student("Roma",20));
      list.add(new Student("Rama",12));
      list.add(new Student("Froger",10));
      list.add(new Student("Raghav",14));
      list.add(new Student("Nammy",11));
      Collections.sort(list);// Sorts the array list

      for(Student a: list)//printing the sorted list of names
         System.out.print(a.getName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Student());
      System.out.println(" ");
      for(Student a: list)//printing the sorted list of ages
         System.out.print(a.getName() +"  : "+
   a.getAge() + ", ");
   }
}

No comments:

Post a Comment