Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is the difference between Comparable & Comparator?

user-image
Question added by muqaddar raza , Senior Software Engineer , i2cinc
Date Posted: 2016/03/23
Sweta Pandey
by Sweta Pandey , Business Analyst , V Logic Labs

Comparable is the interface which works in the Natural Sorting Order of the elements. It is used to compare an object with respect to an attribute. Method is "int compareTo(Object obj,String dept)"

 

Comparator is a interface used for custom sorting order of elements. By this,two objects can be compared to each other with their parameters.  Its method is " int compare(Object obj1,Object obj2)"

 

Prathmesh Halgekar
by Prathmesh Halgekar , Software Engineer , Larsen & Toubro Infotech

Comparator and Comparable both are interfaces. Comparator allows to compare objects on more than one strategy which generally depends on the properties in the objects. Comparable allows only one strategy for a class.

Comparator and Comparable are use when we want the sort function of Collections interface to sort out our user defined objects from the collections passed to the function.

Mohammad Meraj Zia
by Mohammad Meraj Zia , Senior Java Developer , Giffgaff

When your class implements Comparable, the compareTo() method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.