Internals of Comparable and Comparator Interface


Sorting in Java:Comparable and Comparator Interface

One of the most important aspect of every programming language is Sorting. Sorting of Java objects is also becomes  desirable sometimes.In Java,we can get sorted objects by using Comparable or  Comparator interface.

By using Comparable interface:

Comparable interface is one of the most basic entity provided in Java used for sorting.This interface has only one method defined.

public int compareTo(Object o).

There are two steps for getting a sorted list of object.

1.Every class whose object we want to sort should implement this interface and compareTo (Object o) method should be overridden in all the implemented classes.

2.Pass the list of object to a Collections.sort(List list).We will get list of sorted object.

All the basic class like String,Integer,Float,Date implements this interface.So first step is already done.Below example demonstrate this:

package com.devil.space;

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

public class SortingWithComparableExample1 {
	public static void main(String args[]) {
		List<String>animalNameList = new ArrayList<String>();
		animalNameList.add("Tiger");
		animalNameList.add("Lion");
		animalNameList.add("Deer");
		animalNameList.add("Horse");
		Collections.sort(animalNameList);
		for (String name : animalNameList) {
			System.out.println("Animal Name is :- " + name);
		}
	}

}

output of the above code is:

Animal Name is :- Deer
Animal Name is :- Horse
Animal Name is :- Lion
Animal Name is :- Tiger

So here a list of String objects is sorted

Now if we want to sort an object w.r.t some attribute. We can use either Comparable

interface or Comparator interface.Lets Animal is the class whose object we want to sort.

package com.devil.space;

public class Animal implements Comparable<Animal> {

	public String name;
	public Integer age;
	public String sanctuaryName;

	public Animal(String name, Integer age, String sanctuaryName) {
		this.name = name;
		this.age = age;
		this.sanctuaryName = sanctuaryName;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getSanctuaryName() {
		return sanctuaryName;
	}

	public void setSanctuaryName(String sanctuaryName) {
		this.sanctuaryName = sanctuaryName;
	}

	@Override
	public int compareTo(Animal o) {
		 return (this.name.compareTo(o.name));
		//return this.age.compareTo(o.age);
		//return (this.sanctuaryName.compareTo(o.sanctuaryName));

	}

}

package com.devil.space;

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

public class SortingWithComparableExample2 {
	public static void main(String args[]) {
		List<Animal> animalList = new ArrayList<Animal>();
		Animal animal1 = new Animal("Horse", 7,"Corbett");
		Animal animal2 = new Animal("Elephant", 12,"Kajiranga");
		Animal animal3 = new Animal("Tiger", 9, "Ranthambhor");
		animalList.add(animal1);
		animalList.add(animal2);
		animalList.add(animal3);
		Collections.sort(animalList);
		for(Animal animal:animalList){
			System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
		}

	}
}

Output of the above code will be:

Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9—Ranthambhor

Here Animal objects are sorted according to ‘name’ attribute.

Now comment the  line no 41 and remove comment from line no 42 like:

public int compareTo(Animal o) {
		 //return (this.name.compareTo(o.name));
		return this.age.compareTo(o.age);
		//return (this.sanctuaryName.compareTo(o.sanctuaryName));

	}

Now output of the SortingWithComparableExample2 will be:

Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9–Ranthambhor
Animal attributes are: Elephant–12—Kajiranga

Here Animal objects are sorted according to ‘age’ attribute.

Similarly now comment the  line no 42 and remove comment from line no 43  like:

public int compareTo(Animal o) {
		 //return (this.name.compareTo(o.name));
		//return this.age.compareTo(o.age);
		return (this.sanctuaryName.compareTo(o.sanctuaryName));

	}

Now output of the SortingWithComparableExample2 will be:

Animal attributes are: Horse–7–Corbett
Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Tiger–9—Ranthambhor

Here Animal objects are sorted according to ‘sanctuaryName’ attribute.

Now one point can crop up in mind in how  string1.compareTo(String string2)

works internally like line 41,42,43 in Animal Class.Well,it uses lexical order or alphabetically

order for sorting.We can see String class source code to see the exact implementation.

By using Comparator interface:

There are two steps for getting a sorted list of object.

1.First write an Comparator implementation and put our sorting logic in to public int compare(Object o1,Object2) method

2.Pass the list of objects and comparator implementation to  Collections.sort(List list,new NameComparator).We will get list of sorted object.

For the above Animal class example,lets define three Comparator.

1.NameComparator

2.AgeComparator

3.SanctuaryNameComparator

package com.devil.space;

import java.util.Comparator;

public class NameComparator implements Comparator<Animal>{

	@Override
	public int compare(Animal o1, Animal o2) {

		return o1.getName().compareTo(o2.getName());
	}

}
package com.devil.space;

import java.util.Comparator;

public class AgeComparator implements Comparator<Animal> {

	@Override
	public int compare(Animal o1, Animal o2) {
		return o1.getAge().compareTo(o2.getAge());
	}

}
package com.devil.space;

import java.util.Comparator;

public class SanctuaryNameComparator implements Comparator<Animal>{

	@Override
	public int compare(Animal o1, Animal o2) {
		return o1.getSanctuaryName().compareTo(o2.getSanctuaryName());
	}

}

Now lets see how we will use these Comparator:

package com.devil.space;

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

public class SortingWithComparatorExample {
		public static void main(String args[]) {
			List<Animal> animalList = new ArrayList<Animal>();
			Animal animal1 = new Animal("Horse", 7, "Corbett");
			Animal animal2 = new Animal("Elephant", 12,"Kajiranga");
			Animal animal3 = new Animal("Tiger", 9,"Ranthambhor");
			animalList.add(animal1);
			animalList.add(animal2);
			animalList.add(animal3);
			Collections.sort(animalList,new NameComparator());
			for(Animal animal:animalList){
System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
			}
			System.out.println("");
			Collections.sort(animalList,new AgeComparator());
			for(Animal animal:animalList){
System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
			}
			System.out.println("");
			Collections.sort(animalList,new SanctuaryNameComparator());
			for(Animal animal:animalList){
System.out.println("Animal attributes are: "+animal.getName()+"--"+animal.getAge()+"--"+animal.getSanctuaryName());
			}

	}
}

Output of the above code will be:

Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9–Ranthambhor

Animal attributes are: Horse–7–Corbett
Animal attributes are: Tiger–9–Ranthambhor
Animal attributes are: Elephant–12–Kajiranga

Animal attributes are: Horse–7–Corbett
Animal attributes are: Elephant–12–Kajiranga
Animal attributes are: Tiger–9—Ranthambhor

Three set of output are according to which Comparator class we have passed in the Collection.sort()method with the list of objects.First set is sorted according to name,second set is sorted  according to age,third set is sorted according to sanctuaryName.

One thing that we can notice is that in compare(Object o1,Object o2)method,when we put sorting logic of some string,we use compareTo(String s1) .So we can say Comparator is kind

of utility interface whose implementation uses Comparable interface implementation internally

(that is why Comparator is in java.util package and Comparable is in java.lang package).

So lets sum up points:

What is the  difference between Comparable and Comparator interface.

1.WithComparable interface ,we can sort the objects on the basis of one criteria only.

With Comparator,we can get different sorted list on the basis of different sort criteria.

2.With Comparable, we put sorting logic in compareTo() method which needs one parameter,With Camparator,we put sorting logic in compare() which needs two parameter

3.With Comparable interface,developer pass only list of object to Collections.sort (list)method.With Comparator,developer needs to pass a comparator implementation as well,

Like Collections.sort(list,new AgeComparator());

4.Comparable interface is java.lan pacakge and Comparator is in java.util package.

2 thoughts on “Internals of Comparable and Comparator Interface

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s