@FullStackSoftwareQA
Imagine that you a teacher and you are responsible to make each student to stand in order of their height (shorter one first) during morning prayer time. As you are great teacher so you made students comparable i.e. you made them intelligent enough to stand in order of their height on their own by comparing his/her height with other students.
Comparable interface provide same capability to any class. Say You have a class Employee and you want to display all employees in order of length of their name. You can do that by implementing Comparable interface.
Comparable Interface
It’s a core Java interface found in the java.lang package.
Its has only one abstract function compareTo(T o). This method dictates how objects of a class should be compared to each other.
By convention, it returns:
a. A negative integer if the current object is “less than” the other object i.e. this conditions sorts the data in ascending order.
b. Zero if the objects are “equal.”
c. A positive integer if the current object is “greater than” the other object.
Comparator Interface
It’s a core Java interface found in the java.lang package. c
It is FunctionalInterface which has abstract function compare(T o1, T o2). This method dictates how 2 objects of a class should be compared to each other.
By convention, it returns:
a. A negative integer if the o1 “less than” the o2 i.e. this conditions sorts the data in ascending order.
b. Zero if the objects are “equal.”
c. A positive integer if the current o1 is “greater than” the o2.
Conclusion
Comparable and Comparator Interface, both provide mechanism for sorting (or comparing). Difference is that Comparable is in-built within class while Comparator is used to create custom utility outside of the class like we created NameLengthComparator class.
If you want to sort in ascending order then you need to override interfaces’ (Comparator and Comparable) method (compare(T o1, T o2) or compareTo(T o)in such a way that if first object is greater that second object then return 1 else if first object is equal to second object then return 0 else return -1.
Similarly if you want to sort in descending order then you need to override interfaces’ (Comparator and Comparable) method (compare(T o1, T o2) or compareTo(T o)in such a way that if first object is less that second object then return 1 else if first object is equal to second object then return 0 else return -1.
Medium Blog: / comparator-vs-comparable-in-java
Nesta página do site você pode assistir ao vídeo on-line Comparable vs Comparator in Java with implementation example duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário FullStackSoftwareQA 16 Janeiro 2025, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 11 vezes e gostou 1 espectadores. Boa visualização!