The CompareTo()
method for my class is dynamic, and can range from a simple comparison to comparisons on a number of columns. This is all determined at run time, and it works great.
But in some cases, I want any attempt to sort a collection of my objects using the default comparison to just do nothing.
Having CompareTo()
just return a 0 for any comparison, to my surprise, doesn't work. The list gets rearranged in some odd, seemingly-random order.
Is there a way to do this in the CompareTo()
method implementation? I'd rather not handle this up at the collection level by having to override Sort().
In order to change the sorting of the objects according to the need of operation first, we have to implement a Comparable interface in the class and override the compareTo() method.
Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects. To compare movies by Rating, we need to do 3 things : Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo()).
The comparable interface has a method 'compareTo ()' that needs to be overridden in the class implementing the Comparator interface and whose objects are to be sorted. The Comparator interface is used to sort custom objects that are to be sorted based on any other order.
That's because QuickSort is not a stable sort. I don't see a good option to fix this in the CompareTo method unless you can somehow obtain the index of the element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With