Open wentinggy opened 3 years ago
If i remember correctly, comparator has compare method while comparable has compareTo method. I don't think comparator has compareTo method based on the API (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html).
For comparator, you need to implement a compare method while for comparable requires a compareTo method. To add on to the differences between comparator and comparable, we can only use one comparison for comparable while multiple comparisons can be made via invoking different comparator objects
Yup I believe you are right to understand that comparable is used for natural ordering, whereas comparator is used when you want to compare object attributes which may not be naturally ordered. The way I see it was that comparable is a 'simpler' version to compare objects, so if I wanna compare something more intuitive and it can be done with comparable I would use it. But if I'm comparing more complicated objects where the attribute of comparison may not be immediately apparent (eg comparing string names), I would use the comparator.
Hi wentinggy, looks like you have started your revision for finals. Do note that there are times where we choose comparator over comparable.
If i remember correctly, comparator has compare method while comparable has compareTo method. I don't think comparator has compareTo method based on the API (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html).
Oh, I think I got a little confused as the slides in the lecture mentioned that i need to implement comparator to invoke compareTo(?)
Differences : Comparable is where you define the comparing function inside the class. Comparator may be seen as the comparing method itself.
Comparable implemented classes may directly be used in eg. priority queues and you will get a sorted outcome. Comparator may be used to input into eg. priority queues, in case priority queues does not know how to compare your classes.
Examples
class item implements Comparable { @override compareTo(other) { } }
class UnsortedItem { }
new PriorityQueue
new PriorityQueue
Found this pretty useful.
Hi everyone, sorry I'm still a little confused. From my understanding so far (not 100% sure also heh), we use comparator if we want to define our own ordering and use comparable for natural ordering. However, I noticed in the lecture slides that both comparator and comparable have a compareTo method which allows us to define how we want the order of sorting to be done(?) If that's the case, then what is the difference between both if I can decide the way of ordering for both? (sorry if this is a dumb question, I'm quite lost :3)