Tuesday 3 December 2013

Comparable Interface with Example Java

Comparable Interface with Example:

Hi in this post i would like to give you an explanation regarding comparable interface example in java.
Comparable is an interface which belong to java.lang package .Comparable interface helps in ordering of the objects for a class which implements this interface.Here I'm giving you a scenario which explains the comaparable


Q): Using ArrayList take the values of an employee like his name,age,eid and i wanted to get the list to be printed in sorted order as per their names.

Solution: First i created a Employee bean class having getters and setters in it as below.
and implement the Employee class with Comparable interface with Employee as generic type .Implementing comparable will insist you to override the int compareTo(Employee o) method in Employee class

Below is the code snippet Employee.java:
  public class Employee implements Comparable<Employee>{
 private int eid;
 private String ename;
 private int age;
 
 public Employee() {
 }
 public int getEid() {
  return eid;
 }
 public void setEid(int eid) {
  this.eid = eid;
 }
 public String getEname() {
  return ename;
 }
 public void setEname(String ename) {
  this.ename = ename;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 @Override
 public int compareTo(Employee o) {
       
  if(this.ename.compareTo(o.ename)>0)
      
   return 1;
  else if(this.ename.compareTo(o.ename)<0)
   return -1;
  else
   return 0;
 }
Now create a SortEmployee class  where we get the final result of sorted employee details with names. Below is the code snippet SortEmployee.java:  
import java.util.ArrayList;

import java.util.Collections;

public class SortEmployee {
 public static void main(String args[]){
 
     Employee naveen=new Employee();
  naveen.setAge(24);
  naveen.setEid(1);
  naveen.setEname("naveen");
  Employee vivek=new Employee();
  vivek.setAge(32);
  vivek.setEid(2);
  vivek.setEname("vivek");
  Employee check=new Employee();
  check.setAge(44);
  check.setEid(3);
  check.setEname("piyush");
 ArrayList<Employee> emps=new ArrayList<Employee>();

 emps.add(naveen);
 emps.add(vivek);
 emps.add(check);

  Collections.sort(emps);
  
  for(Employee emp1:emps){
   System.out.println(emp1.getEname()+">>>>"+emp1.getAge()+">>>>"+emp1.getEid());
  }
 }
}

Now if we run the SortEmployee.java we get the desired output as below:
naveen>>>>24>>>>1
piyush>>>>44>>>>>3
vivek>>>>32>>>>2

To sort the employee details based on age change compareTo method as below and re run the program :
 @Override
 public int compareTo(Employee o) {
  
  if(this.age>o.age)
   return 1;
  else if(this.age<o.age)
   return -1;
  else
   return 0;
 }
output:
naveen>>>>24>>>>1
vivek>>>>32>>>>2
piyush>>>>44>>>>3

No comments:

Post a Comment