Friday, October 10, 2008

Comparing object and sorting them in java using Comparator and Comparable interfaces

As we know sorting is one of the very common tasks especially when we have a list or collection of objects. For example if we have a list of Employees then we would like to display it in some order may be by sorting them by EmpId or name. In these situations both (Comparator and Comparable) will become handy.

About Comparators and Comparables

Simply putting java.lang.Comparator and java.lang.Comparable are used for comparing objects in java.

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.lang.Comparator interface.

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.

Now lets see how we can use these interfaces

Each of these has one method to be implemented by user.

java.lang.Comparable: int compareTo(Object obj1)
This method compares this object with obj1 object. Returned int value has the following meanings.

  1. positive – this object is greater than obj1
  2. zero – this object equals to obj1
  3. negative – this object is less than obj1


java.lang.Comparator: int compare(Object obj1, Object obj2)
This method compares obj1 and obj2 objects. Returned int value has the following meanings.

  1. positive – obj1 is greater than obj2
  2. zero – obj1 equals to obj2
  3. negative – obj1 is less than obj1

Note:

java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.

Now let’s do a simple example to see these concepts in real scenario.

(1) First we will write a simple Employee class as below..

public class Employee {

private int empId;

private String name;

public Employee(int empId, String name) {

this.empId=empId;

this.name=name;

}

public int getEmpId() {

return empId;

}

public void setEmpId(int empId) {

this.empId = empId;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

(2) Next we will write a class to implement compare() method of comparator interface. You can see below in the code that we are comparing Employee object by name attribute. Instead of name we can use Empid attribute to compare objects for sorting. The choice depends on the need.

public class NameComparator implements Comparator{

public int compare(Object emp1, Object emp2) {

String emp1Name = ( (Employee) emp1).getName();

String emp2Name = ( (Employee) emp2).getName();

return emp1Name.compareTo(emp2Name);

}

}

(3) Finally we will write a test class to use our NameComparator class for comparing and sorting Employee objects.

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashSet;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

public class TestEmployeeSort {

public static void main(String args[]){

//create a set of Employee object without any specific order

Set<Employee> set = new HashSet<Employee>();

set.add(new Employee(3, "Raj"));

set.add(new Employee(1, "Sajid"));

set.add(new Employee(6, "Sowmya"));

set.add(new Employee(2, "Manu"));

set.add(new Employee(7, "Larry"));

set.add(new Employee(4, "Suresh" ));

set.add(new Employee(8, "Harry"));

set.add(new Employee(5, "Ashu"));

//converting set to list

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

System.out.println("Order of employee before sorting is");

Iterator i=list.iterator();

while(i.hasNext())

{

Employee e1=(Employee) i.next();

System.out.println(e1.getEmpId() + "\t" + e1.getName() );

}

//calling sort method and passing the list of employees and a new instance of our NameComparator class

Collections.sort(list,new NameComparator());

System.out.println("Order of employee after sorting is");

for (Employee e: list) {

System.out.println(e.getEmpId() + "\t" + e.getName() );

}

}

}

After running this test class we would get following output.

Order of employee before sorting is

3 Raj

8 Harry

6 Sowmya

1 Sajid

4 Suresh

5 Ashu

7 Larry

2 Manu

Order of employee after sorting is

5 Ashu

8 Harry

7 Larry

2 Manu

3 Raj

1 Sajid

6 Sowmya

4 Suresh

Send free SMS using Google Labs SMS channel

Google Labs in India (http://labs.google.co.in/ ) have launched their latest mobile service named Google SMS channel. This service is designed to enable users to send free group SMS messages across India. The good thing is that they currently support messages in several languages including English, Hindi, Kannada etc. You can receive alerts for latest news, cricket updates, blog feeds, daily quotes, horoscope , jokes, news from MoneyControl, and lot more and all for free.

I think it would be a great way to connect 200+ million mobile subscribers in India who still don’t have access to valuable information. Subscribers to this service can join as many as 30 channels but they will not receive more than 10 SMS messages a day. Other features are like message senders can send the message using a web based interface and the subscribers can set the time when they want to receive the messages.

I am also planning to create one SMS channel to connect with friends and family..

Visit the FAQ section (http://labs.google.co.in/smschannels/help ) for more details.

Enjoy sending free SMS to your friends and family members.

Popular Posts