Thursday, June 28, 2012

Sample Program for Comparable and Comparator


Comparator and Comparable in Java are two of fundamental interface of Java API which is very important to understand to implement sorting in Java. It’s often required to sort objects stored in any collection class or in Array and that time .

Comparable:

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
        1. positive – this object is greater than o1
        2. negative – this object is less than o1
        3. Zero – this object equals to o1
java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.


Sample Code:
package com.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingObjectList {
public static void main(String[] args) {
Employee emp1 = new Employee();
emp1.setAge(12);
emp1.setFirstName("Eswar");
emp1.setLastName("Palani");
emp1.setEmpId(13);
List<Employee> sortList = new ArrayList<Employee>();
sortList.add(emp1);
Employee emp2 = new Employee();
emp2.setAge(34);
emp2.setEmpId(15);
emp2.setFirstName("Karthi");
emp2.setLastName("Palani");
sortList.add(emp2);
Employee emp3 = new Employee();
emp3.setAge(50);
emp3.setEmpId(15);
emp3.setFirstName("Aru");
emp3.setLastName("Palani");
sortList.add(emp3);
Collections.sort(sortList);
System.out.println("The sorted lists are======>");
for (Employee employee : sortList) {
System.out.println(employee.getFirstName()+" "+employee.getLastName());
}
}

}

class Employee implements Comparable<Employee>{
private String firstName;
private String lastName;
private int age;
private int empId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Employee o) {
if (o.firstName.equals(this.firstName))
if (o.age-this.age == 0)
return o.empId - this.empId;
else
return o.age-this.age;
else
return o.firstName.compareTo(this.firstName);
}
}

Output:
The sorted lists are======>
Karthi Palani
Eswar Palani
Aru Palani

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
          1. positive – this object is greater than o1
          2. negative – this object is less than o1
          3. Zero – this object equals to o1
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.

Sample Code:


package com.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortingObjectListComparator {

public static void main(String[] args) {
Staff emp1 = new Staff();
emp1.setAge(12);
emp1.setFirstName("Eswar");
emp1.setLastName("Palani");
emp1.setEmpId(13);
List<Staff> sortList = new ArrayList<Staff>();
sortList.add(emp1);
Staff emp2 = new Staff();
emp2.setAge(34);
emp2.setEmpId(15);
emp2.setFirstName("Karthi");
emp2.setLastName("Palani");
sortList.add(emp2);
Staff emp3 = new Staff();
emp3.setAge(50);
emp3.setEmpId(15);
emp3.setFirstName("Aru");
emp3.setLastName("Palani");
sortList.add(emp3);
Collections.sort(sortList, new Staff());
System.out.println("The sorted lists are===");
for (Staff staff : sortList) {
System.out.println(staff.getFirstName()+" "+staff.getLastName());
}
}

}


class Staff implements Comparator<Staff>{
private String firstName;
private String lastName;
private int age;
private int empId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compare(Staff o1, Staff o2) {
return o1.getFirstName().compareTo(o2.getFirstName());
}
}

output:

The sorted lists are===
Aru Palani
Eswar Palani
Karthi Palani



Difference between Comparator and Comparable:

1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.

2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

6)Objects which implement Comparable in Java  can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

1 comment:

  1. There's definately a great deal to know about this topic. I like all the points you've made.

    ReplyDelete