Open yongchein-o opened 2 years ago
Comparable interface tells Java how to compare instances of classes that you have defined. Imlist::sort() takes in a comparator, so you still have to create a comparator class and use your compareTo (from comparable) to tell java how you want to sort the list. I think the point is just to simplify code? Like to abide by abstraction and encapsulation.
Referring to Lecture 5 slide 14, you need to create a class that implements Comparator
It might seem redundant to define methods for both Comparator and Comparable, but as LauWyeRock mentioned, I believe it is probably to abide by encapsulation to have it clearly defined within the Booking class itself
I would believe that Comparable also helps to simplify the comparing process as it sorts by checking whether the difference between two values are negative, == to 0 or positive. Hence you can use very simple code like turn this.A - other.A;
Alternatively, you can use comparator. I find it easier in my opinion. Comparator works very similarly to comparable when you define the method. Note that comparator uses a "compare(Booking b1, Booking b2)" while comparable uses a "compareTo". if you use comparator, make sure to initialise it in the jsh file: "BookingComparator bkComp = new BookingComparator();" and you can proceed to just "bookings = bookings.sort(bkComp);"
Alternatively, you can use comparator. I find it easier in my opinion. Comparator works very similarly to comparable when you define the method. Note that comparator uses a "compare(Booking b1, Booking b2)" while comparable uses a "compareTo". if you use comparator, make sure to initialise it in the jsh file: "BookingComparator bkComp = new BookingComparator();" and you can proceed to just "bookings = bookings.sort(bkComp);"
Or you can use a lambda expression without creating the BookingComparator class
Summary
Description of the question / problem here. Hi does anyone know what is the point of implementing comparable? If I have an ImList of Booking, how do I sort it using the fact that Booking implemented comparable?
I'd expect that there might be a sort method to like Sort an ImList of Bookings at Level 6....
Description:
Clarifications or details with respect to the issue you are facing
Code Snippets
Attach code snippets (if any)
Screenshots
Screenshots (if any)