Friday, August 9, 2013

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 difference between them, major difference between Comparable and Comparator is that former is used to define natural ordering of object e.g. lexicographic order for java.lang.String, while later is used to define any alternative ordering for an object.  Main usage of java.lang.Comparable and java.util.Comparator interface is for sorting list of objects in Java. For example to sort a list of Employee by there Id, we can use Comparable interface and to provide additional sorting capability, we can define multiple comparators e.g. AgeComparator to compare age of employee, SalaryComparator to compare salary of employees etc.  This brings another important difference between Comparator and Comparable interface in Java, you can have only one ordering 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 on 2 to 3 years experience 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 difference between Comparator vs Comparable in Java from interview perspective.


Comparator vs Comparable in Java

Difference between Comparator and comparable in JavaDuring interviews, you can face this question differently, if you are giving telephonic round than it's mostly fact based i.e. you need to mention key points about both interfaces, while in face to face interviews or during written test, you might be ask to write code to sort objects using Comparator and Comparable e.g. sorting employee by name or branch. I have already discussed 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 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.

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 implementation, 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 than compareTo() and compare() must return zero. Failing to adhere 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 difference between Comparator and Comparable in Java. Always remember that java.lang.Comparable is used to define natural ordering of an object, while java.util.Comparator can be used to define any ordering based upon your requirements. You can define only one ordering with Comparable but can have multiple Comparators. I strongly suggest to look 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
Difference between List, Set, and Map in Java
Difference between HashMap and HashSet in Java
Difference between Path and Classpath in Java
When to extend thread and implement Runnable in Java
Difference between wait and sleep method in Java

3 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

Java67 Headline Animator