Difference between Comparator and Comparable

Asked

Viewed 795 times

1

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

2 answers

2


Comparable: If you have control over the class’s source code, you can implement this interface in it to define a standard sorting strategy. Example: if you have a class of Person, you can implement Comparable in it defining an order by name, as it is a widely used criterion to sort People, therefore, it may be the pattern (natural).

Comparator: It is useful when you need to create custom sorts. You can have a class with a standard sorting strategy (implementing Comparable in it) and in situations where it is necessary to sort differently, create n classes that implement Comparator to meet these cases that the default class ordering does not meet. Following the class example Person which sorts by default by name, it may happen that in a specific situation you need to sort, for example, People by decreasing age and by mother’s name. There you implement a Comparator for this class.

Summary:

  • You have a standard sorting strategy and can change the class? Comparable is a good option.
  • You need to define multiple sorting strategies or you cannot define the default sorting strategy in the class because you cannot change it? Comparator.

0

The Comparable allows you to say a comparison rule for the class that implements this interface, as a kind of standard rule or official rule, while if you want to escape from this standard rule, you can create your comparison classes, which will extend the class Comparator making each one its own rule.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.