nus-cs2030 / 2122-s2

CS2030 repository and wiki for AY 2021/2022 Sem 2
MIT License
0 stars 0 forks source link

Comparators vs Comparables #97

Open muhdjabir opened 2 years ago

muhdjabir commented 2 years ago

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?

alantay11 commented 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.

jingyulim1 commented 2 years ago

There is another discussion here which you may find helpful.

TohDeKai commented 2 years ago

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/

GraceYongXM commented 2 years ago

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)