Saturday 28 May 2016

Write Comparator for Student class, assuming student class has name and roll number.


Question:-

Write comparator for Student class, assuming student class has name and roll number.

           Conditions:

                   If the name is same, check of roll number

                   If the name is different, check only for name



Sample Program:-


import java.util.Comparator;  
 /**  
  * Comparator for Student class which uses following field for comparison  
  *   
  * 1.Name ,If name are same, then it uses Roll Number.  
  *   
  * If Name are different , then it checks for name only.  
  *   
  * @author   
  *  
  */  
 public class StudentComparator implements Comparator<Student> {  
   @Override  
   public int compare(Student student1, Student student2) {  
    if (student1 != null && student2 != null) {  
      String name1 = student1.getName().trim();  
      String name2 = student2.getName().trim();  
      if (name1.equals(name2)) {  
       return student1.getRollNumber() - student2.getRollNumber();  
      }  
      return name1.compareTo(name2);  
    }  
    return 0;  
   }  
 }  

Enjoy Programming :)

No comments:

Post a Comment