Comparable & Comparator:

Comparable & Comparator:

  • Comparable and Comparator both are interfaces and are used to do sorting in Collection framework.
  • Comparable is used for single sorting where as Comparator is used or multiple sorting.
  • I will discuss comparable first and its uses with examples then after we will go for Comparator.

Comparable Interface in java:

  • It is used to order the objects of user defined classes in defined order.
  • Comparable interface is in java.lang package and its having one method compareTo(Object) which takes user defined object as argument.
  • It provides Single sorting only that means you can sort the elements on based on single data member only.
  • compareTo() method compares current object data member with the specified object. The return type of the method is int.
  • Based on the return value that is (+ve,0,-ve) collection will sort the objects.
  • Lets go for a sample program and i will explain step by step.
public class Employee implements Comparable<Employee>{

int id;

String name;

double salary;

 

@Override

public int compareTo(Employee emp) {

 

return this.id-emp.id;

}

 

}

 

  • Here I wrote a Employee class which implements Comparable interface and I overridden compareTo()
  • Here I compared on a data member called “id” and retrned difference of the two employee object ids.
  • Now i will write the clint class where i will insert employee objects into a collection type and will sort it.
package com.tcoj.clint;

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.Iterator;

import java.util.List;

 

import com.tcoj.model.Employee;

 

public class Clint {

 

public static void main(String[] args) {

List<Employee> list=new ArrayList<Employee>();

Employee emp1=new Employee(102, “shaswot”, 11500.89);

Employee emp2=new Employee(100, “subham”, 12500.89);

Employee emp3=new Employee(107, “ashok”, 11500.99);

Employee emp4=new Employee(103, “rahul”, 13501.09);

 

list.add(emp1);

list.add(emp2);

list.add(emp3);

list.add(emp4);

Collections.sort(list);

Iterator<Employee> itr=list.iterator();

while(itr.hasNext())

{

System.out.println(itr.next());

}

}

 

}

 

  • Here I created one List and added 4 employee objects.
  • When i called Collections.sort() method it sorted according to the compareTo() method defined in Employee class.

OUTPUT:

 

[100,subham,12500.89]

[102,shaswot,11500.89]

[103,rahul,13501.09]

[107,ashok,11500.99]

It sorted according to id of Employee.You guys can try with name and salary.Let me know with comments if you guys having any doubt on this part.Next topic Comparators.

 

6 Comments

Leave a reply to nikhil Cancel reply