TudorT
TudorT

Reputation: 476

Collections.sort with Comparator returning constant

How bad of an idea is to reorder an ArrayList using ?

Collections.sort(list, descendingComparator );

where parameters are:

ArrayList<Map> list;

descendingComparator = new Comparator<Map>() {
    @Override
    public int compare(Map lhs, Map rhs) {
        return -1;
    }
};

It seems to work, and the number of steps are not infinite, but I am worried that this is OS version dependent.

Upvotes: 0

Views: 647

Answers (1)

user439793
user439793

Reputation:

This is a bad idea, because the compare() method is supposed to work both ways: if a < b then b > a which this comparator will not do. If compare() does not work like this, the results are undefined behavior. It might work, it might not, and maybe not consistently.

The ideal way is to wrap another comparator in one that reverses it:

final Comparator<Map> someOtherComparator = ...;
descendingComparator = new Comparator<Map>() {
    @Override
    public int compare(Map lhs, Map rhs) {
        // Note the parameters are swapped here
        return someOtherComparator.compare(rhs, lhs);
    }
};

You could also do this:

Collections.sort(list, comparator);
Collections.reverse(list);

Finally, if your list elements have a natural ordering (implements Comparable, which Map does not), you can do this:

Collections.sort(list, Collections.reverseOrder());

Upvotes: 3

Related Questions