Skip to main content

Difference between Comparable and Comparator in Java

You always been in confusion to differentiate the differences between these two things.
Actually speaking Comparable and Comparator are both the Interfaces in Java.
Both are since Jdk version 1.2 means quite old still enough to confuse us so far.

Basically, the purpose of these two interfaces is to compare two objects.

Now you might wondering why we need another class or interface just to compare objects when we already have equals() method in Object class?

So, let me give you some background so you better understand the purpose of existence of these interfaces and eventually we will also see the benefits of each one over another plus when to use which interface.

Okay!

The Background...

I hope you might aware about collection framework in java. Collections are objects in java which does the job of container for objects and which theoretically holds unlimited objects. now typed collections holds only the objects which having same type of which collection is. List, Set and Map are top collection interfaces in java.

I wont go in much details to explain more these collection interfaces since for now its out of syllabus for us.

The Need...

So, we know collections right? and its natural to be have sorted list of items or objects most of the time when we present the data to the user.

Now equals() method only check whether the two objects are same or not...this method wont tell you or give you enough information that whether object is smaller or greater.

hmmm....

Thats why we need a somebody who can tell when we have lots of objects in our container to be ordered in sorted manner.
So Java added these two interfaces.

Why two...wasn't one interface enough?

ummm....yeah one can be enough but you know java people are way smarted and always look for reusability...hence second Comparator interface born sake of reusability purpose.

Comparable...

This interface belongs to java.lang package and has only one compareTo method.
Below i have added the implementation of Comparable interface.

If you closely observe above code snippet, you might see syntax<T> ahead of Comparable, which is generics support.
This means you can create Comparable interface for any type of objects.
Also notice the return type of compareTo method. it's int right u saw?

So let me tell you purpose of int return type here.

1. When method compareTo returns 0 means the interface implementing object and object received in compareTo method are equals.
2. When method returns 1 means interface implementing object is greater than received object.
and you have guessed it correct...
3. When method return -1 means interface implementing object is smaller than received object.

now most of the thing has been cleared right....

and added to this Comparator is same companion of comparable with little difference and added purpose...but it follows same strategy to give insight of object was smaller, equal or greater basis on returned int value[1 , 0 , -1].

To compare objects, corresponding objects classes must implement the Comparable interface.

let me explain you with Student example, i have list of Students objects and i wanted sort it based on rank.
so my Comparable implementation in Student class would be like this.

Comparator...

Unlike Comparable, Comparator interface belongs to java.util package.

Like Comparable, Comparator interface is also having only one method, name compare(), but the difference is method compare() has two argument unlike compareTo() which had only one argument in its method signature.
below is implementation for Comparator interface to add more clarity on same Student example.

Now, if you notice above code snippet, compare() method accepts two objects to compare, that means to compare with Comparator it is not necessary a class has to implement Comparator to compare itself with other objects like Comparable, thus you can create as many Comparator implementation as you wish based on Objects property and use it for different different comparison of same object.

Above we see that we sorted Students collections based on ranking, now if new requirement comes up and now you want to sort same Students collections based on Students age, hence solution is to create another Comparator implementation which compares Students based on age.
Have a look to below code snippet for this.

Now you have understood why second interface Comparator has born for sake of reusability.

The Application...

So far we have read all the background, need, purpose, blah blah and blah blah...
lets see applications of these two interfaces.

To sort the collections like list or set or any type of Collection, we have java.util.Collections.sort() method which sorts the collections.

sort() method is overloaded method in Collections class.
lets see Comparable use:

Output:
We have successfully compared the two Students based on rank, but what if we want to sort same list of Students with their name? or their Age ?
So lets make use of Comparator here, we will be creating two separate Comparator each for Age and Name.
Output:
You understood the purpose of Comparable and Comparator very well, right!
So when you want to compare objects, implement Comparable interface and when you want to compare same object based on different properties of it then create separate property Comparator and sort the Collection.

Comments

Popular posts from this blog

Lambda expression in Java 8

Behaviour Parameterisation …pattern which allows you to write such a flexible code which can cope up with any requirement change. Now you may wondering why I am talking about this weird sounding pattern instead lambda expression, right? Well, let me tell you that we will soon get to know about lambda expression in detail but understanding Behaviour Parameterization  pattern will definitely help you thoroughly how lambda expression is useful to write concise and succinct code and you will start feeling power of lambda expression which is one of prime feature of java 8 release. Lets say, we have list of Books and you need to find Books with greater than 200 pages. You could write a method getBooksGreaterThanPages(): Using this method is simple enough, what if you need to find books smaller than 200 pages? Or Books above particular prices? Or Books from particular author or publications? Or even worst book with particular publication with certain pages and below particular pric

Default Methods in Java 8

Adding new methods in interface s always break the implementation in class. So Java 8 come up with new feature which propose a mechanism to extend existing interfaces by adding new methods without breaking existing implementation thus, achieved the backward compatibility. Default methods is the feature which helps you to extend existing interfaces . If added method in interface provides the default implementation then no implementing Class get affects.   Default methods enable you to add new functionality to the interfaces of your libraries and ensure  binary compatibility with code written for older version of those interfaces. An implementing class can override the default implementation defined in implemented interface  and add its own implementation. To understand it with example, lets say there is ABC company which wants to launch their smart Radios in market, so they have developed  SmartRadio interface(contract) and ABCRadio final product implements all the fu

Reference data type in java

Unlike Primitive data types in java, Reference data type store the address of object in memory which they refer to, than actual value. lets say, Car class is already defined, and its object is created in memory then variable declared with type Car becomes the reference type which will be holding address of car object to which it refers. Car car = new Car(); int noOfDoors = 4; Car myCar = car; // copy the car reference into myCar reference . Here, variable car actually contains the address and variable noOfDoors will contain actual 4 value. See below diagram for more explanation: Reference data type holding address of object in heap memory and primitive data type holds actual primitive values Available reference types in java: Class type Interface type array type e.g. String name = new String("Java"); List listOfNames = new ArrayList(); Students topRankers[] = new Student[10]; Remember though you know now that Reference data type holds