What are advantages of comparator in Java over comparable?

(Last Updated On: February 25, 2019)

Answer includes advantages of comparator over comparable interfaces and difference between both in Java collections. Note that advantages  of comparator over coparable and when would you use comparable and comparator interface is a frequently asked java interview question. You may read what is comparable and comparator interface in java collections before reading difference and advantages.

Answer:

Comparable Vs Comparator Interface:

  • A class must implement the comparable interface if sorting required on collection of objects, but, for comparator we don’t need to implement it.
  • By using comparator, objects can be sorted based on more than one fields of a class. Whereas Comparable allows you to sort items in a collections based on only one field.
Tips
For this type of questions in an interview, most of the people just tells the points but don’t explain it. It is always better to explain with some scenarios or situations where it is useful. It gives an interviewer, a clear indication that you have good command over it.

 

Advantages of comparator over comparable

One of the good advantage of comparator interface is that by using comparator interface, we can provide comparison algorithms to other existing classes or classes that are not allowed to modified for some reason for example a class that is provided by Vendor or something.This is not possible with using comparable interface.

In other words,

If we use the comparable interface, a class is required to implement it. But, consider a scenario where modification in a class is not allowed. Specifically, we are not allowed to implement any interface for a class. For example

  • A class could be a compiled class already that cannot be modified. So, cannot use comparable interface.
  • A class had been written long time back where sorting on this class objects was not the intention at that time. So, implementation of comparable interface was not done. And also, it might be possible that multiple classes might have been derived from it. So, if this class implements comparable interface, all derived classes are forced to implement it as well. So, using comparable interface here is also a bad idea.

So for above scenarios, comparator interface is the only or good option, where we can write a custom comparator classes and implement comparator interface and then use it for sorting collection of objects of the class.