Reputation: 3361
This may seem like a dumb question, but I'd like to inquire about the best way to sort in reverse order a sortable structure (any kind, could be List
) of a class MyClass
that doesn't implement Comparable
First off, since MyClass
doesn't implement Comparable
and I want to sort it, I create a Comparator
, something like this:
public class MyClassComparator implements Comparator<MyClass> {
@Override
public int compare(MyClass o1, MyClass o2) {
return (o1.getMyField()).compareTo(o2.getMyField());
}
}
This, of course, sorts MyClass objects according to the natural ordering of MyClass.MyField. But I want the reverse order.
I could of course just hardcode the reverse order in the compare(MyClass o1, MyClass o2)
method. Something like
if (o1.getMyField()).compareTo(o2.getMyField()) > 0 return -1;
if (o1.getMyField()).compareTo(o2.getMyField()) < 0 return 1;
return 0;
Anoter alternative is leaving the code of MyClassComparator as I initially suggested, and using public static <T> Comparator<T> reverseOrder(Comparator<T> cmp)
from java.util.Collections
to pass an instance of MyClassComparator
and get a reverse comparator.
And a third alternative, that I think is wrong, could be sorting my LinkedList<MyClass>
with the natural order Comparator and fetch the elements from last to first. LinkedList
is a doubly linked list, so it should handle this perfectly. The problem is that I would always have to get a specific Iterator
instead of just using a for each
loop (minor) and, of course, that I initially wanted to sort ANY sortable structure, and I can't guarantee that it will be a doubly linked list or anything that handles well iterating through it in reverse order.
Considering that I'm quite certain (can't ever be 100% certain) that I won't be using the natural order of MyClass
objects, just the reverse order, what would be the best way to obtain my reverse comparator?
Thank you.
Upvotes: 0
Views: 789
Reputation: 106
Using a comparator would be the correct approach here in order to avoid the overhead of reversing an array. If the classes you are comparing implement Comparable you can just reverse the order of the comparison. obj2.compareTo(obj1)
. A way to visualize this is to think of the two objects as integers and compareTo as subtracting them.
Upvotes: 1