Sunday, December 10, 2017

Sorting Objects | Comparable

While developing any java application, many time we need to sort our objects. Java provides two different mechanism to sort your objects.
  1. Comparable
  2. Comparator 
Comparable is an interface comes with compare() method. This is used to compare one instance of a class with other object of same class. The class needs implement Comparable interface to become comparable.  Compare method return -1, 0 or 1. 
Let’s have Student class example. Create two object s1 and s2. => -1 if s1 is smaller then s2
                         =>  0 if s1 equals to s2
                         =>  1 if s1 is greater then s2
Check code example of Student class implementing comparable interface. You can try with different comparison logic by updating compare logic inside compare() method.

public class Student implements Comparable<Student> {

       private String name;
       private String level;
       private int rollNum;

       public int compareTo(Student s) {
             // Write your logic to check ordering of you object
             // You must return -1, 0, 1 on the basis of object1 is less, equal or
             // greater than this object
             if (s.getRollNum() < this.rollNum) {
                    return -1;
             } else if (s.getRollNum() == this.rollNum) {
                    return 0;
             } else
                    return 1;

       public String getName() {
             return name;

       public void setName(String name) {
    = name;

       public String getLevel() {
             return level;

       public void setLevel(String level) {
             this.level = level;

       public int getRollNum() {
             return rollNum;

       public void setRollNum(int rollNum) {
             this.rollNum = rollNum;


Pros & Cons:   
  • Comparable interface allows you to compare two objects.
  • For using comparable you do not need to create any separate class, you can just provide your sorting logic inside compare method of your existing class.
  • It provides very tight coupling, If in future you want to write any other criteria for comparing your objects you have to modify your class.
  • You can provide only a single comparison logic in your comparable class.
  • You must have access to the code, if you don't have code of class, and you want to write your comparison logic for that class, you can't do that.

As you see there are some issues with Comparable interface, we can overcome these problems using Comparator interface.

Please Click Herefor learning Comparator.


Post a Comment