Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effectively disable Sort() within a CompareTo() override?

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().

like image 312
richardtallent Avatar asked Mar 09 '10 23:03

richardtallent


People also ask

Why do we override compareTo method?

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.

Does collections sort use compareTo?

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()).

Which of the given method must be overridden by class after implementing comparator?

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.


1 Answers

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.

like image 148
Hans Passant Avatar answered Oct 04 '22 23:10

Hans Passant