When should a class be Comparable and/or Comparator?

JavaComparatorComparable

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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).

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

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.

Solution 10 - Java

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.

Solution 11 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick HeinerView Question on Stackoverflow
Solution 1 - JavaDanView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaKLEView Answer on Stackoverflow
Solution 4 - JavacodiacTushkiView Answer on Stackoverflow
Solution 5 - JavastarblueView Answer on Stackoverflow
Solution 6 - JavaMichael MyersView Answer on Stackoverflow
Solution 7 - JavajavapassionView Answer on Stackoverflow
Solution 8 - JavaMichael Lloyd Lee mlkView Answer on Stackoverflow
Solution 9 - JavaSravaniChowdary.GorijavoluView Answer on Stackoverflow
Solution 10 - JavaSrinivasView Answer on Stackoverflow
Solution 11 - JavaJianmin LiuView Answer on Stackoverflow