简体   繁体   English

具有Comparator返回常量的Collections.sort

[英]Collections.sort with Comparator returning constant

How bad of an idea is to reorder an ArrayList using ? 使用ArrayList重新排序的想法有多糟糕?

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. 似乎可行,并且步数不是无限的,但是我担心这取决于OS版本。

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. 这是一个坏主意,因为compare()方法应该同时起作用:如果a < b那么b > a该比较器将不起作用。 If compare() does not work like this, the results are undefined behavior. 如果compare()不能这样工作,则结果是未定义的行为。 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: 最后,如果您的列表元素具有自然的顺序(实现Comparable ,而Map没有实现),则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM