Reputation: 5
Collections.sort(list, new Comparator<A>() {
@Override
public int compare(A a, A b) {
return -a.getId().compareTo(b.getId());
}
});
If you put a minus in front of the return value in the comparator, will it correspond to reverseOrder method?
Collections.sort(list, Collections.reverseOrder(new Comparator<A>() {
@Override
public int compare(A a, A b) {
return a.getId().compareTo(b.getId());
}
}));
I mean, will it always work right?
Upvotes: 0
Views: 103
Reputation: 140484
-Integer.MIN_VALUE
is also Integer.MIN_VALUE
.
If you can guarantee that compareTo
can't return Integer.MIN_VALUE
, it will work the same (assuming the compareTo
method is implemented correctly).
Otherwise, it would be safer to use the reverseOrder
method, or to swap a
and b
in the expression (which is what reverseOrder
does).
Upvotes: 6