Tuesday 6 December 2016

Why to implement Comparable?

Why to implement Comparable?
If you are a Java developer, I am sure that, you already implemented Comparable interface in some of your projects. By implementing Comparable
Interface, you can impose natural ordering of elements, while sorting.

Comparable interface provides ‘compareTo’ method, all the implemented classes must provide definition to ‘compareTo’ method.

int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

If your class implements Comparable interface, you can use Java built in classes like Arrays.sort(), Collections.sort() to sort the elements in their natural order. Let me give an example of Comparable interface first, later we can see the advantages of implementing Comparable interface.

Example: Sort employees by id
Employee.java
public class Employee implements Comparable<Employee> {

 private String firstName, lastName;
 private Integer id;

 Employee(String firstName, String lastName, int id) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.id = id;
 }

 @Override
 public int compareTo(Employee o) {
  if (o == null)
   throw new NullPointerException();
  return this.id.compareTo(o.id);
 }

 @Override
 public String toString() {
  return id + ". " + firstName + " " + lastName;
 }

}

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

public class EmployeeTest {
 public static void main(String args[]) {
  List<Employee> myList = new ArrayList<>();

  myList.add(new Employee("Joel", "Abc", 5));
  myList.add(new Employee("Murali", "Krishna", 3));
  myList.add(new Employee("Gopi", "battu", 4));
  myList.add(new Employee("Rama", "Krishna", 2));

  System.out.println("Before Sorting");
  Iterator<Employee> iter1 = myList.iterator();
  while (iter1.hasNext()) {
   System.out.println(iter1.next());
  }

  Collections.sort(myList);

  System.out.println("\nAfter Sorting");
  Iterator<Employee> iter2 = myList.iterator();
  while (iter2.hasNext()) {
   System.out.println(iter2.next());
  }

 }
}

Output
Before Sorting
5. Joel Abc
3. Murali Krishna
4. Gopi battu
2. Rama Krishna

After Sorting
2. Rama Krishna
3. Murali Krishna
4. Gopi battu
5. Joel Abc

By implementing Comparable interface, you can provide implementation to generic algorithms. For example, you can implement quick sort once and it can be used with all the data types that implement Comparable.

Following are some of the examples of generic algorithms that implement Comparable interface.


Collections like TreeSet, PriorityBlockingQueue stores elements in their natural ordering. You can specify the natural ordering by implementing Comparable interface.

By implementing Comparable interface, you can use the utility classes provided by Java like Collections.sort, Arrays.sort, PriorityBlockingQueue

If you would like to know about the difference between Comparable, Comparator you can go through following post.


You may like




No comments:

Post a Comment