Comparable vs. Comparator in Java

Comparable and Comparator are two interfaces provided by Java Core API. From their names, we can tell they may be used for comparing stuff in some way. But what exactly are they and what is the difference between them? The following are two examples for answering this question. The simple examples compare two HDTV's size. How to use Comparable vs. Comparator is obvious after reading the code.

1. Comparable

Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo(). Here is an example:

class HDTV implements Comparable<HDTV> {
	private int size;
	private String brand;
 
	public HDTV(int size, String brand) {
		this.size = size;
		this.brand = brand;
	}
 
	public int getSize() {
		return size;
	}
 
	public void setSize(int size) {
		this.size = size;
	}
 
	public String getBrand() {
		return brand;
	}
 
	public void setBrand(String brand) {
		this.brand = brand;
	}
 
	@Override
	public int compareTo(HDTV tv) {
 
		if (this.getSize() > tv.getSize())
			return 1;
		else if (this.getSize() < tv.getSize())
			return -1;
		else
			return 0;
	}
}
 
public class Main {
	public static void main(String[] args) {
		HDTV tv1 = new HDTV(55, "Samsung");
		HDTV tv2 = new HDTV(60, "Sony");
 
		if (tv1.compareTo(tv2) > 0) {
			System.out.println(tv1.getBrand() + " is better.");
		} else {
			System.out.println(tv2.getBrand() + " is better.");
		}
	}
}
Sony is better.

2. Comparator

In some situations, you may not want to change a class and make it comparable. In such cases, Comparator can be used if you want to compare objects based on certain attributes/fields. For example, 2 persons can be compared based on `height` or `age` etc. (this can not be done using comparable.)

The method required to implement is compare(). Now let's use another way to compare those TV by size. One common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
 
class HDTV {
	private int size;
	private String brand;
 
	public HDTV(int size, String brand) {
		this.size = size;
		this.brand = brand;
	}
 
	public int getSize() {
		return size;
	}
 
	public void setSize(int size) {
		this.size = size;
	}
 
	public String getBrand() {
		return brand;
	}
 
	public void setBrand(String brand) {
		this.brand = brand;
	}
}
 
class SizeComparator implements Comparator<HDTV> {
	@Override
	public int compare(HDTV tv1, HDTV tv2) {
		int tv1Size = tv1.getSize();
		int tv2Size = tv2.getSize();
 
		if (tv1Size > tv2Size) {
			return 1;
		} else if (tv1Size < tv2Size) {
			return -1;
		} else {
			return 0;
		}
	}
}
 
public class Main {
	public static void main(String[] args) {
		HDTV tv1 = new HDTV(55, "Samsung");
		HDTV tv2 = new HDTV(60, "Sony");
		HDTV tv3 = new HDTV(42, "Panasonic");
 
		ArrayList<HDTV> al = new ArrayList<HDTV>();
		al.add(tv1);
		al.add(tv2);
		al.add(tv3);
 
		Collections.sort(al, new SizeComparator());
		for (HDTV a : al) {
			System.out.println(a.getBrand());
		}
	}
}

Output:

Panasonic
Samsung
Sony

Often we may use Collections.reverseOrder() method to get a descending order Comparator. Like the following:

ArrayList<Integer> al = new ArrayList<Integer>();
al.add(3);
al.add(1);
al.add(2);
System.out.println(al);
Collections.sort(al);
System.out.println(al);
 
Comparator<Integer> comparator = Collections.reverseOrder();
Collections.sort(al,comparator);
System.out.println(al);

Output:

[3,1,2]
[1,2,3]
[3,2,1]

3. When to use Which?

In brief, a class that implements Comparable will be comparable, which means it instances can be compared with each other.

A class that implements Comparator will be used in mainly two situations: 1) It can be passed to a sort method, such as Collections.sort() or Arrays.sort(), to allow precise control over the sort order and 2) It can also be used to control the order of certain data structures, such as sorted sets (e.g. TreeSet) or sorted maps (e.g., TreeMap).

For example, to create a TreeSet. We can either pass the constructor a comparator or make the object class comparable.

Approach 1 - TreeSet(Comparator comparator)

class Dog {
	int size;
 
	Dog(int s) {
		size = s;
	}
}
 
class SizeComparator implements Comparator<Dog> {
	@Override
	public int compare(Dog d1, Dog d2) {
		return d1.size - d2.size;
	}
}
 
public class ImpComparable {
	public static void main(String[] args) {
		TreeSet<Dog> d = new TreeSet<Dog>(new SizeComparator()); // pass comparator
		d.add(new Dog(1));
		d.add(new Dog(2));
		d.add(new Dog(1));
	}
}

Approach 2 - Implement Comparable

class Dog implements Comparable<Dog>{
	int size;
 
	Dog(int s) {
		size = s;
	}
 
	@Override
	public int compareTo(Dog o) {
		return o.size - this.size;
	}
}
 
public class ImpComparable {
	public static void main(String[] args) {
		TreeSet<Dog> d = new TreeSet<Dog>();
		d.add(new Dog(1));
		d.add(new Dog(2));
		d.add(new Dog(1));
	}
}

References:
1. Comparable
2. Comparator

Category >> Common Methods >> Versus  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Venu Sabbani

    we can add comparator logic with ananymous method way ..

    package com.venu.comparator;

    import java.util.*;

    import java.io.*;

    class Simple{

    public static void main(String args[]){

    ArrayList al=new ArrayList();

    al.add(new Student(101,”Vijay”,23));

    al.add(new Student(106,”Ajay”,27));

    al.add(new Student(105,”Jai”,21));

    System.out.println(“Sorting by Name…”);

    Collections.sort(al,new Comparator() {

    @Override

    public int compare(Student o1, Student o2) {

    // TODO Auto-generated method stub

    return o1.name.compareTo(o2.name);

    }

    });

    Iterator abs = al.iterator();

    while(abs.hasNext()){

    Student x = (Student) abs.next();

    System.out.println(“the values ” + x.age + “the names” + x.name + “the roll no” + x.rollno);

    }

    Collections.sort(al,new Comparator() {

    @Override

    public int compare(Student o1, Student o2) {

    // TODO Auto-generated method stub

    if(o1.age == o2.age)

    return 0;

    else if(o1.age >o2.age)

    return 1;

    else

    return -1;

    }

    });

    Iterator agecmp = al.iterator();

    while(agecmp.hasNext()){

    Student x = (Student) agecmp.next();

    System.out.println(x.rollno+” “+x.name+” “+x.age);

    }

    }

    }

    //POJO Class

    package com.venu.comparator;
    class Student{
    int rollno;
    String name;
    int age;

    public int getRollno() {
    return rollno;
    }

    public void setRollno(int rollno) {
    this.rollno = rollno;
    }

    public String getName() {
    return name;
    }

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

    public int getAge() {
    return age;
    }

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

    Student(int rollno,String name,int age){
    this.rollno=rollno;
    this.name=name;
    this.age=age;
    }

    }

  • Comparable defines the natural ordering for the class objects….If we need any other ordering then we have to define comparator. Since comparator is not tied to a class so we can have several comparators depicting different sort (based on the fields) sequences for the same class…

    See a post about differences here – http://netjs.blogspot.com/2015/10/difference-between-comparable-and-comparator-java.html

  • thank you it is useful post.i also refer very helpful and useful article about–Sorting using Comparator in Java
    Please visit this article———-

    http://www.mindstick.com/Articles/a4872d1a-6316-42b8-b431-7b48107cb7db/Sorting%20using%20Comparator%20in%20Java#.VekynJc0Xcc
    http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

  • Raghavendra Madipakkam

    Hi

  • Anurag Chaturvedi

    What I feel, that when you are creating new class and which needs to be sorted or compared, it should be implemented by Comparable and if we have some pre-developed class and need to add functinality for compare or sorting, then we need to create a class implemented by Comprator and use this class as a parameter in sort method.

  • Anil Nivargi

    Thanks good explaination….Here another blog also explained nice please go through this blog http://adnjavainterview.blogspot.in/2014/06/difference-between-comparable.html

  • Micheal

    hi and one more doubt is Collections.sort(al, new SizeComparator());
    what is this actually doing
    my guess sizecomparatorobject.compare(obj1 of al,obj2 of al)
    by the use of result returned by the above compare method (i.e)1,-1,0 how sorting will be done?

  • Micheal

    hi my doubt about this tutorial is

    why we are going for comparator/comparable interface? it is possible for us to define such comparision method inside our class and can call it by the use of instance of its own.

    class SizeComparator implements Comparator {
    @Override
    public int compare(HDTV tv1, HDTV tv2) {
    int tv1Size = tv1.getSize();
    int tv2Size = tv2.getSize();

    if (tv1Size > tv2Size) {
    return 1;
    } else if (tv1Size < tv2Size) {
    return -1;
    } else {
    return 0;
    }
    }
    }
    instead of this it is possible to have our own method?

  • om

    good example

  • n

    alert(0);

  • ryanlr

    True. Changed.

  • kk

    Under Heading 2.Comparator
    “Comparator is capable of comparing two DIFFERENT types of objects.”
    EDIT: Comparator is capable if comparing objects based on different attributes. e.g. 2 men can be compared based on `name` or `age` etc. (this can not be done using comparable. ) Even in the example shown above, author provides example where object of SAME type (HDTV) is being used.

  • Sachin P

    Two ways for sorting – using comparator and comparable. For detailed explanation is here

  • ven

    Nice one.