Difference between Comparator and Comparable

1

In Java, what is the difference between these two interfaces, Comparator and Comparable? When to use one or the other?

    
asked by anonymous 09.11.2018 / 11:24

3 answers

1

Comparable: If you have control over the source code of the class, you can implement this interface on it to define a default sort strategy. Example: If you have a Person class, you can implement Comparable in it by setting a sort by name, as it is a commonly used criteria for sorting People >, so it can be the default (natural).

Comparator: This is useful when you need to create custom sorts. You can have a class with a standard sort strategy (implementing Comparable in it) and in situations that require different sort ordering, create n classes that implement Comparator to handle such cases that the default sort order does not match. Following the example of the Person class that sorts by name by default, it may happen that in a specific situation you need to sort, for example, People by descending age and by the name of the mother . Then you implement a Comparator for this class.

Summary:

  • Do you have a standard sort strategy and can you change the class? Comparable is a good option.
  • You need to define several sorting strategies or you can not define the default sorting strategy in the class, why can not you change it? Comparator .
09.11.2018 / 13:33
0
Comparable allows you to tell a comparison rule for the class that implements this interface, as a sort of standard rule or official rule, whereas if you want to evade this standard rule, you can create your comparator classes, which will extend the Comparator class by making each their own rule.

    
09.11.2018 / 11:33
-1

Comparable - It's an interface. Comparator - It is a method of this interface. some type implement the Comparable interface, so already have the Comparator method as an example we have the Wrapper, which basically is a class that represents a primitive type. Integer, Float, Double, String

    
10.11.2018 / 00:48