Open muhdjabir opened 2 years ago
From what I understand, comparable is implemented by a class you want to compare, while comparator is defined outside the actual class. Comparator is useful if you need to compare them in different ways since you can create multiple comparators for the same class.
There is another discussion here which you may find helpful.
A comparable object is capable of comparing itself with another object.
Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members.
You can read about it more in depth here: https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/
the sorting sequence of comparator and comparable are different! source: [https://www.javatpoint.com/difference-between-comparable-and-comparator]
and since comparator is a separate class whereas comparable has to be implemented by the class itself, comparator can be more general and useful as the same comparator class can be used across different classes (my own interpretation tho)
Hello everyone, recalled the existence of both Comparator and Comparable interfaces. I am quite clueless as to the fundamental difference between these two interfaces as they seem quite similar. What is the core difference between these two interfaces and Is there an ideal situation in which a Comparator would be implemented over a Comparable and vice versa?