Difference between Comparator and Comparable in Java - Interview Question

Comparator and Comparable are two interfaces in Java API, which is used to compare two objects in Java. Though both are used for comparison there are some differences between them, a major difference between Comparable and Comparator is that the former is used to define the natural ordering of objects e.g. lexicographic order for java.lang.String, while later is used to define any alternative ordering for an object.  The main usage of java.lang.Comparable and java.util.Comparator interface is for sorting a list of objects in Java.

For example, to sort a list of Employees by their Id, we can use a Comparable interface and provide the additional sorting capability, we can define multiple comparators e.g. AgeComparator to compare the age of the employee, SalaryComparator to compare the salary of employees, etc.  

Difference between Comparator and comparable in JavaThis brings another important difference between Comparator and Comparable interface in Java, you can have only one order via Comparable e.g. natural ordering while you can define multiple Comparator for alternative ordering as discussed above.

Coming to Interviews, this question is very common in 2 to 3 years of experience in Java interviews, and you just can't afford to not prepare this. It's definitely possible to achieve years of experience in Java, without writing your own Comparator or Comparable, especially if you are not doing active development or coding, but even though, you must know basics e.g. equals and hashcode, compareTo() and compare().

In this article, we will see some notable differences between Comparator vs Comparable in Java from an interview perspective. If you are preparing for Java Interview, you may like to see this nice book, Java Programming Interview Exposed by Markham, an excellent book with Java interview questions for both intermediate and experienced Java programmers.




Comparator vs Comparable in Java

During interviews, you can face this question differently, if you are giving a telephonic round then it's mostly fact-based i.e. you need to mention key points about both interfaces, while in the face to face interviews or during the written test, you might be asked to write code to sort objects using Comparator and Comparable e.g. sorting employee by name or branch. I have already discussed the second part of this question here and we will only see fact-based differences in this post.

1. Comparator interface is in java.util package, which implies it's a utility class, while Comparable interface is kept on java.lang package, which means it's essential for Java objects.

2. Based on syntax, one difference between Comparable and Comparator in Java is that former gives us compareTo(Object toCompare), which accepts an object, which now uses Generics from Java 1.5 onwards, while Comparator defines compare(Object obj1, Object obj2) method for comparing two object.

3. Continuing from the previous difference between Comparator vs Comparable later is used to compare current object, represented by this keyword, with another object, while Comparator compares two arbitrary objects passed to compare() method in Java.

4. One of the key difference between Comparator and Comparable interface in Java is that, You can only have one compareTo() implementation for an object, while you can define multiple Comparator for comparing objects on different parameters e.g. for an Employee object, you can use compareTo() method to compare Employees on id,  known as natural ordering, while multiple compare() method to order employee on age, salary, name and city. It's also a best practice to declare Comparator as nested static classes in Java, because they are closely associated with objects they compare.

5. Many Java classes, which make uses of Comparator and Comparable defaults to Comparable and provided overloaded method to work with arbitrary Comparator instance e.g. Collections.sort() method, which is used to sort Collection in Java has two implementations, one which sort object based on natural order i.e. by using java.lang.Comparable and other which accepts an implementation of java.util.Comparator interface.

6. One more key thing, which is not a difference but worth remembering is that both compareTo() and compare() method in Java must be consistent with equals() implementation i.e. if two methods are equal by equals() method then compareTo() and compare() must return zero. Failing to adhere to this guideline, your object may break invariants of Java collection classes which rely on compare() or compareTo() e.g. TreeSet and TreeMap.



That's all on the difference between Comparator and Comparable in Java. Always remember that java.lang.Comparable is used to define the natural ordering of an object, while java.util.Comparator can be used to define any order based upon your requirements. You can define only one ordering with Comparable but can have multiple Comparators. I strongly suggest looking my example of comparator vs comparable to gain more insight on how to use really use it in code. From Java interview point of view, I think, you are good to go if you know this much details.


Other Java Interview Questions articles from Java67 Blog

8 comments:

  1. Nice 1,It really good explaination

    ReplyDelete
  2. Use Comparable to provide default ordering and Use Comparator to provide custom ordering, as simple as that.

    ReplyDelete
  3. Very neat and clear explanation. Thank you so much for the great Knowledge share

    ReplyDelete
  4. Like we can have multiple comparators why cant we have multiple compareTo functions by making them in static nested classes??

    ReplyDelete
  5. I think you switched the two terms (Comparator vs Comparable) in the 3rd paragraph,

    "3. Continuing from previous difference between Comparator vs Comparable, former is used to compare current object, represented by this keyword, with another object, while Comparator compares two arbitrary object passed to compare() method in Java."

    Because the word "former" should mean the first item (so here Comparator), but in reality, you meant "Comparable". So maybe it's better to write "Comparable vs Comparator", or use the word "latter" instead of "former".

    Anyway, thank you very much for this article!

    ReplyDelete
    Replies
    1. @Anonymous, thanks for pointing this out, correct it now.

      Delete
  6. Really good for interview point of view..👍

    ReplyDelete
    Replies
    1. @Narendra, thanks. The article is written from interview point of view but knowing the difference between them, also help you to decide when to use Comparator over Comparable or vice-versa.

      Delete

Feel free to comment, ask questions if you have any doubt.