pudge pudge - 7 months ago 12
Java Question

ArrayList - Creating comparators

I created an ArrayList that contains references to objects that contain various amounts of data.

I wish to sort the object by certain elements of their data.

I successfully did so using the

collections.sort
along with an anonymous class defining the new comparator.

I was successful in each of the new comparators I created which resulted in correct sorted order.

For the same ArrayList how could you make a comparator that would give the original input of the ArrayList order. I know that the ArrayList saves the order of the objects they are added, insertion order. But after sorting the ArrayList with other comparators, how would I then sort the ArrayList back to the original order that it was in? This is the one thing that is stumping me, and I can't seem to figure it out.

Edit: I should clarify this is for an assignment, in which the instructions say to include a default/original comparator to get the unsorted input. That just doesn't make sense to me, given what we mentioned. The ArrayList will save the insertion order when it is added, but when you sort that it is lost. i don't see how you could create a comparator that will sort what the original list was.

Edit2: I am given an ArrayList which is expected to store a few objects that contain some data elements which will be sorted, such as by their names or their age. This comparators were easy to make and I do so successfully. The assignment also wants to an original comparator that display the data as it was inserted. Now these comparators are being passed in a method call, in which that method will use the collections.sort on each different comparator. It is asking for the original comparator to be used first though.

The idea of the original comparator at all seems illogical. The fact that is being used first, so no other sorting has been done yet makes it seem that it was only made so it fits the argument list of calling the method to display the data. So in other words, I guess the original comparator should just return nothing..?

Answer

It is asking for the original comparator to be used first though.

This means that the comparator doesn't need to restore the original order, which is what wouldn't make any sense (impossible), but to do nothing when used to sort, i.e. leave the original order unchanged.

Quoting javadoc of sort():

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

This means that if you pass in a comparator that claims all objects to be equal, no reordered will take place.

// Java 8 example using lambda expression
Collections.sort(list, (a,b) -> 0); // No-op. All elements compare equal
Comments