Organizational Research By

Surprising Reserch Topic

when to use comparable and comparator

when to use comparable and comparator  using -'java,comparator,comparable'

I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works.

Now looking back at this, I am wondering if I should have instead have the my class implement Comparable instead of creating a new class that implements Comparator. The score is the only field that the objects will be ordered on.

What I have done acceptable as a practice?
Is the right approach "First have the class implement Comparable (for the natural ordering) and if an alternative field comparison is required, then create a new class that implements Comparator" ?
If (2) above is true, then does it mean that one should implement Comparator only after they have the class implement Comparable? (Assuming I own the original class).


asked Oct 7, 2015 by ajit.chavhan
0 votes

Related Hot Questions

15 Answers

0 votes

I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.

If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option.

Put another way, given the class name, is it clear how a comparable would sort, or do you have to resort to reading the javadoc? If it is the latter, odds are every future sorting use case would require a comparator, at which point the implementation of comparable may slow down users of the class, not speed them up.

answered Oct 7, 2015 by kotmus2002
0 votes

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.

Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.

answered Oct 7, 2015 by dhananjayksharma
0 votes

Use Comparable:

  • if the object is in your control.
  • if the comparing behaviour is the main comparing behaviour.

Use Comparator :

  • if the object is outside your control and you cannot make them implement Comparable.
  • when you want comparing behaviour different from the default (which is specified by Comparable) behaviour.
answered Oct 7, 2015 by virendra.bajaj
0 votes

I would say:

  • if the comparison is intuitive, then by all means implement Comparable
  • if it is unclear wether your comparison is intuitive, use a Comparator as it's more explicit and thus more clear for the poor soul who has to maintain the code
  • if there is more than one intuitive comparison possible I'd prefer a Comparator, possibly build by a factory method in the class to be compared.
  • if the comparison is special purpose, use Comparator
answered Oct 7, 2015 by rolvyrf
0 votes

Comparable should be used when you compare instances of same class.

Comparator can be used to compare instances of different classes.

Comparable is implemented by class which need to define a natural ordering for its objects. Like String implements Comparable.

In case one wants a different sorting order then he can implement comparator and define its own way of comparing two instances.

answered Oct 7, 2015 by rajesh
0 votes
  • If at the moment of writing the class you have only one use case of sorting use Comparable.
  • Only when you have more than one strategy of sorting implement a Comparator.
answered Oct 7, 2015 by shikhar jain
0 votes

There had been a similar question here: questions/1440134/java-what-is-the-difference-between-implementing-comparable-and-comparator

I would say the following: Implement Comparable for something like a natural ordering, e.g. based on an internal ID

Implement a Comparator if you have a more complex comparing algorithm, e.g. multiple fields and so on.

answered Oct 7, 2015 by suyesh.lokhande
0 votes

If you need natural order sorting -- User Comparable IF you need Custom Order Sorting - Use Comparator


Class Employee{
private int id;
private String name;
private String department;

Natural order Sorting would be based on id because it would be unique and custom order sortin g would be name and department.

Java: What is the difference between implementing Comparable and Comparator?

answered Oct 7, 2015 by deepak
0 votes

Whenever we want to store only homogeneous elements and default natural sorting order required, we can go for class implementing comparable interface.

Whenever we want to store homogeneous and heterogeneous elements and we want to sort in default customized sorting order, we can go for comparator interface.

answered Oct 7, 2015 by abhi
0 votes

Comparator does everything that comparable does, plus more.

| | Comparable | Comparator ._______________________________________________________________________________ Is used to allow Collections.sort to work | yes | yes Can compare multiple fields | yes | yes Lives inside the class you’re comparing and serves | | as a “default” way to compare | yes | yes Can live outside the class you’re comparing | no | yes Can have multiple instances with different method names | no | yes Input arguments can be a list of | just Object| Any type Can use enums | no | yes

I found the best approach to use comparators as anonymous classes as follows:

private static void sortAccountsByPriority(List accounts) {
    Collections.sort(accounts, new Comparator() {

        public int compare(AccountRecord a1, AccountRecord a2) {
            return a1.getRank().compareTo(a2.getRank());

You can create multiple versions of such methods right inside the class you’re planning to sort. So you can have:

  • sortAccountsByPriority
  • sortAccountsByType
  • sortAccountsByPriorityAndType


Now, you can use these sort methods anywhere and get code reuse. This gives me everything a comparable would, plus more ... so I don’t see any reason to use comparable at all.

answered Oct 7, 2015 by okesh.badhiye
0 votes

Very simple approach is to assume that the entity class in question be represented in database and then in database table would you need index made up of fields of entity class? If answer is yes then implement comparable and use the index field(s) for natural sorting order. In all other cases use comparator.

answered Oct 7, 2015 by akhilesh
0 votes

If you own the class better go with Comparable. Generally Comparator is used if you dont own the class but you have to use it a TreeSet or TreeMap because Comparator can be passed as a parameter in the conctructor of TreeSet or TreeMap. You can see how to use Comparator and Comparable in

answered Oct 7, 2015 by rajeevr642
0 votes

My need was sort based on date.

So, I used Comparable and it worked easily for me.

public int compareTo(GoogleCalendarBean o) {
    // TODO Auto-generated method stub
    return eventdate.compareTo(o.getEventdate());

One restriction with Comparable is that they cannot used for Collections other than List.

answered Oct 7, 2015 by bhavin
0 votes

** Comparable && Comparator **

public class Employee implements Comparable{

    private int id;
    private String name;
    private int age;
    private long salary;

    // Static Field.
    public static Comparator NameComparator = new Comparator() {         
        public int compare(Employee e1, Employee e2) {
            return e1.getName().compareTo(e2.getName());
    public static Comparator idComparator = new Comparator() {       
        public int compare(Employee e1, Employee e2) {
            return Integer.valueOf(e1.getId()).compareTo(Integer.valueOf(e2.getId()));

    public Employee() { }
    public Employee(int id, String name, int age, long salary){ = id; = name;
        this.age = age;
        this.salary = salary;
// setters and getters.
    public int compareTo(Employee e) {
//return Integer.valueOf(;
//return Character.toString(;
        if ( > {
            return 1;
        }else if( <{
            return -1;
        }else {
            return Character.toString(;

public static void main(String[] args) {        

        Employee e1 = new Employee(5, "Yash", 22, 1000);
        Employee e2 = new Employee(8, "Tharun", 24, 25000); ….
List list = new ArrayList();
Collections.sort(list); // call @compareTo(o1)
Collections.sort(list, Employee.nameComparator); // call @compare (o1,o2)
Collections.sort(list, Employee.idComparator); // call @compare (o1,o2)
  • For customised sorting we go for comparator @compare(o1, o2) for other senarios we go for comparable @compareTo(o1), with out changing code if we want to sort more than one field then we use comparator.
answered Oct 7, 2015 by mtabakade
0 votes

I have been asked sorting of a definite range of numbers in better than nlogn time in one of interview. (Not using Counting sort)

Implementing Comparable interface over an object allows implicit sorting algos to use overridden compareTo method to order sort elements and that would be linear time.

answered Oct 7, 2015 by vijayshukla80