java.util.Comparable vs java.util.Comparator Intefaces in Java

The java.util.Comparable and java.util.Comparator interfaces together with the java.util.Collections allow the user to sort a List. An implementation of the Comparable interface allows the user to create a specific strategy to compare with another object(which should be mutually comparable). For example:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Employee implements Comparable
{
private String name;
private int age;

public Employee(String name, int age)
{
this.name = name;
this.age = age;
}

public int compareTo(Employee e)
{
//comparison strategy
}


}

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main
{
public static void main(String[] args)
{
List employeeList = new ArrayList();
employeeList.add( new Employee("Tim", 10) );
employeeList.add( new Employee("Rolvin", 11) );
employeeList.add( new Employee("Gerald", 12) );

Collections.sort(employeeList);

}
}


the Comparator on the other hand doesn't tie you with a single comparison strategy. The java.util.Collections class has an overloaded sort method(i.e. other than sort(List) that accepts a List and a Comparator as an argument. For the sake of this example, I will not be providing any code for the implemented methods. But just to let you know that the compareTo() method for Comparable and the compare() method for the Comparator interfaces both return an int value. Just to guide you what value you should return here is a guide based on the K & B book for SCJP 5.0

obj1 < obj1 ="=""> obj2, return a positive value

Ok, so as we can see from the above example, we are tied with the Employee class's implementation of compareTo(). If we wanted to sort by employee names, we'd be tied to that for the rest of our lives(unless of course you subclass Employee). This is where the Comparator interface comes in handy. With the Comparator interface you are not tied to a single implementation. So if we wanted to sort the employeeList by name or by age we could create separate classes for each of those.

1
2
3
4
5
6
7
public class SortByName implements Comparator
{
public int compare(Employee e1, Employee e2)
{
//comparison strategy here
}
}


1
2
3
4
5
6
7
public class SortByAge implements Comparator
{
public int compare(Employee e1, Employee e2)
{
//comparison strategy here
}
}


and finally be able to use it like this

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args)
{
List employeeList = new ArrayList();
employeeList.add( new Employee("Tim", 10) );
employeeList.add( new Employee("Rolvin", 11) );
employeeList.add( new Employee("Gerald", 12) );

Collections.sort(employeeList, new SortByName() );//sort by name;
Collections.sort(employeeList, new SortByAge() );//sort by age;

}






0 comments: