Sunday, February 8, 2015

Use java Comparable interface to sort objects

In previous tutorial we looked at how to sort int, double and String arrays using java Arrays.sort() method. That is not all that we can do with that method. We can sort Objects as well.
But when we come to Objects there is a small problem. Lets see that problem and solution for that using java Comparable Interface.

This is the code for Student class
public class Student {

 private String name;
 private int marks; 

 public Student(String name,int marks){
  this.name=name;
  this.marks=marks;
 } 

 public void setName(String name) {
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setMarks(int marks) {
  this.marks = marks;
 }

 public int getMarks() {
  return marks;
 }
}


If we create few objects of Student class and try to sort them using Arrays.sort() method,
  
public class ObjSort {

 public static void main(String args[]){ 

  Student[] students = new Student[4];

  Student pineappale = new Student("nimal", 70);
  Student apple = new Student("Anuradha", 95);
  Student orange = new Student("Tharaka", 82); 
  Student banana = new Student("Isuru", 90); 

  students[0]=pineappale;
  students[1]=apple;
  students[2]=orange;
  students[3]=banana; 

  //sort with student's marks 
  Arrays.sort(students); 

  int i=0;
  for(Student temp: students){
   System.out.println("Students " + ++i + " : " + temp.getName() +
   ", Marks : " + temp.getMarks());
  }
    }
}

It will give an error because to sort there should be something to compare. But in Student objects there are multiple attributes to compare. To sort objects on particular attribute we have to implement Comparable class and override the  compareTo() method in Student class.
After making those differences it will look like this.
 
public class Student implements Comparable<Student> { 

 private String name;
 private int marks; 

 public Student(String name,int marks){
  this.name=name;
  this.marks=marks;
 }  

 public void setName(String name) {
  this.name = name;
 }
 public String getName() {
  return name;
 }

 public void setMarks(int marks) {
  this.marks = marks;
 }

 public int getMarks() {
  return marks;
 } 

 public int compareTo(Student compStudent) { 
  int comparemark = compStudent.getMarks(); 

  //if we want to sort in ascending order
  return this.marks - comparemark; 
 } 
}

Now we can use Arrays.sort() method on array of Student objects because now it compares objects on marks attribute.

1 comment:

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...