In Java, what is the difference between these two interfaces, Comparator and Comparable? When to use one or the other?
In Java, what is the difference between these two interfaces, Comparator and Comparable? When to use one or the other?
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:
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