146

I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?

yeaaaahhhh..hamf hamf
  • 746
  • 2
  • 13
  • 34
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • 18
    Have you read the javadoc on them? It describes the different quite clearly. – skaffman Sep 17 '09 at 17:10
  • 1
    What is comparable and comparator and when to use comparable and comparator. To know these read this link. this will help you to understand their behavior and usage. [http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html](http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html) – RockStar Oct 26 '12 at 02:14
  • 6
    This is a good question with a good, objective answer. I am dismayed that it is closed. – Russell Silva Jul 23 '13 at 19:46
  • 3
    [Other questions](http://stackoverflow.com/questions/4108604/java-comparable-vs-comparator) on StackOverflow refer to this as the definitive "What's the difference between comparator and comparable" question. Why is it marked as "not constructive"? As a Java Newbie, this was a very useful question! – Pete Sep 28 '14 at 16:06
  • http://www.experts-exchange.com/Programming/Languages/Java/A_2523-Java-Collections-Comparable-Vs-Comparator.html – akjain Jan 02 '15 at 05:57
  • Comparable for Natural/Default sorting. And Comparator for Customized sorting – rahulnikhare Jan 23 '18 at 05:53
  • I think of it this way. Comparable provides a default way to a class to compare two objects of itself. Comparator provides custom ways to compare two objects of same type. Hotel has Customers. Customer who spends more money is more important. Special offers go to top 10% customers only. But sometimes, we want to encourage the lowest spending customers to spend more. Then, we can compare by lesser money spent, get bottom 5% users & send special offers to them also. – MasterJoe Apr 09 '20 at 00:27

11 Answers11

245

The text below comes from Comparator vs Comparable

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176
Dan
  • 3,777
  • 4
  • 25
  • 23
  • for detailed explanation of the uses of both Comparator and comparable: http://sysdotoutdotprint.com/index.php/2017/03/28/comparable-vs-comparator/ – mel3kings Mar 28 '17 at 03:49
  • 2
    Another good article: https://web.archive.org/web/20180707182116/http://codecramp.com/java-comparable-vs-comparator/ – EMM Aug 09 '17 at 01:42
  • @mel3kings Can you please update the link in your comment? It currently provides no information towards this question. – CJay Horton May 08 '22 at 16:56
161

Implementing Comparable means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.

Implementing Comparator means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.

roottraveller
  • 7,942
  • 7
  • 60
  • 65
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Hello skeet, can you please drop the code using comparable and comparator. – Mdhar9e May 15 '12 at 14:03
  • 5
    @mdhar9e: There are lots of examples around - if you're finding it difficult to translate them into your specific scenario, please give more information in a new question. – Jon Skeet May 15 '12 at 14:07
  • @JonSkeet Can you please give an example that a scenario implemented by `Comparator` can't be implemented by `Comparable` easily? I don't see much difference between them – Alireza Farahani Jun 30 '14 at 11:45
  • 2
    @alireza: I've already given an example in the second paragraph: by having different comparators, you could sort the same collection (people) by different properties (age, name etc). You can't do that just by making `Person` implement `Comparable`, because you can't then change *how* two people are compared. – Jon Skeet Jun 30 '14 at 11:46
  • @Jon Skeet Thank you very much for your explaination.Can you provide some real time example ? – Nagappa L M Aug 11 '14 at 06:28
  • @jon Skeet Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted.Is this mean applying differant sorting methods like bubble,quick etc sorts ? – Nagappa L M Aug 11 '14 at 06:50
  • 1
    @feelgoodandprogramming: No, those are different sorting *algorithms*. There are potentially three pieces of code here, in three different classes: 1) The entity itself, e.g. `Person`. 2) The comparator, e.g. `PersonAgeComparator` which is able to compare two different entities and decide which should come first in that particular sort order. 3) The sort code, which takes a collection of entities and a comparator, and sorts that collection using the comparator to determine the order. – Jon Skeet Aug 11 '14 at 08:02
  • @JonSkeet let me know my understanding is correct or not. 1) use Comparable when i want to compare only on any one of them, age or name. And 2) use Comparator when i want to use age and name both. means if Comparator will find the age to be same it will compare name. – RishiKesh Pathak Dec 08 '14 at 12:29
  • 2
    @RishiKeshPathak: Well it's more that you use Comparable if there is only one single obvious thing to compare on. And even then you *can* just write a Comparator. If you have two different programs using the same class, and one wants to sort by just age and the other by just name, at least *one* of them will need to use a Comparator. – Jon Skeet Dec 08 '14 at 12:53
  • 1
    @JonSkeet you mean, we are good even without Comparable. Only advantage it gives is more readable code? – RishiKesh Pathak Dec 08 '14 at 13:35
  • 1
    @RishiKeshPathak: Yes, most APIs support providing an explicit comparator - it's just that it's a bit of extra cruft to do so, if there's one obvious ordering. – Jon Skeet Dec 08 '14 at 14:04
39

Comparable lets a class implement its own comparison:

  • it's in the same class (it is often an advantage)
  • there can be only one implementation (so you can't use that if you want two different cases)

By comparison, Comparator is an external comparison:

  • it is typically in a unique instance (either in the same class or in another place)
  • you name each implementation with the way you want to sort things
  • you can provide comparators for classes that you do not control
  • the implementation is usable even if the first object is null

In both implementations, you can still choose to what you want to be compared. With generics, you can declare so, and have it checked at compile-time. This improves safety, but it is also a challenge to determine the appropriate value.

As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though ! :-(

  • Comparable<Object> lets you use it in all codes at compile-time (which is good if needed, or bad if not and you loose the compile-time error) ; your implementation has to cope with objects, and cast as needed but in a robust way.
  • Comparable<Itself> is very strict on the contrary.

Funny, when you subclass Itself to Subclass, Subclass must also be Comparable and be robust about it (or it would break Liskov Principle, and give you runtime errors).

Rich Seller
  • 83,208
  • 23
  • 172
  • 177
KLE
  • 23,689
  • 4
  • 56
  • 62
21

java.lang.Comparable

  1. To implement Comparable interface, class must implement a single method compareTo()

    int a.compareTo(b)

  2. You must modify the class whose instance you want to sort. So that only one sort sequence can be created per class.

java.util.Comparator

  1. To implement Comparator interface, class must implement a single method compare()

    int compare (a,b)

  2. You build a class separate from class whose instance you want to sort. So that multiple sort sequence can be created per class.
codiacTushki
  • 750
  • 1
  • 9
  • 22
14

Comparable is for providing a default ordering on data objects, for example if the data objects have a natural order.

A Comparator represents the ordering itself for a specific use.

starblue
  • 55,348
  • 14
  • 97
  • 151
8

Comparable is usually preferred. But sometimes a class already implements Comparable, but you want to sort on a different property. Then you're forced to use a Comparator.

Some classes actually provide Comparators for common cases; for instance, Strings are by default case-sensitive when sorted, but there is also a static Comparator called CASE_INSENSITIVE_ORDER.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • 7
    I'm not sure I agree with Comparable being preferred. Some objects have a strong sense of natural order—namely numbers, in all their forms: natural numbers, real numbers, dates, etc. But even other relatively primitive objects like character strings lack a universally applicable order. In the case of more complex objects like an entity from an application domain model, implementing Comparable is usually a mistake. Their many properties make it too difficult to anticipate what order will be wanted most often. – erickson Sep 17 '09 at 17:39
6

here are few differences between Comparator and Comparable I found on web :

  1. If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

  2. Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

  3. If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method.

  4. Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

site:How to use Comparator and Comparable in Java? With example

Read more: How to use Comparator and Comparable in Java? With example

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
javapassion
  • 61
  • 1
  • 1
5

Comparable is for objects with a natural ordering. The object itself knows how it is to be ordered.
Comparator is for objects without a natural ordering or when you wish to use a different ordering.

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
4

Difference between Comparator and Comparable interfaces

Comparable is used to compare itself by using with another object.

Comparator is used to compare two datatypes are objects.

Ravi
  • 30,829
  • 42
  • 119
  • 173
2

If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by compareTo method.

Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

mbinette
  • 5,094
  • 3
  • 24
  • 32
Srinivas
  • 51
  • 1
0

My annotation lib for implementing Comparable and Comparator:

public class Person implements Comparable<Person> {         
    private String firstName;  
    private String lastName;         
    private int age;         
    private char gentle;         

    @Override         
    @CompaProperties({ @CompaProperty(property = "lastName"),              
        @CompaProperty(property = "age",  order = Order.DSC) })           
    public int compareTo(Person person) {                 
        return Compamatic.doComparasion(this, person);         
    }  
} 

Click the link to see more examples. compamatic

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
  • 3
    Welcome to stackoverflow. This question is old and was already answered. Typically, it is best not to resurrect stale threads unless your response contributes something significantly new or different over previous answers. – oers Oct 29 '12 at 08:11