简体   繁体   English

覆盖比较器和 Collections.sort

[英]Overridden comparator and Collections.sort

        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?如果在比较器的返回值前面加上一个减号,会不会对应reverseOrder方法?

        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?我的意思是,它会一直正常工作吗?

-Integer.MIN_VALUE is also Integer.MIN_VALUE . -Integer.MIN_VALUE也是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).如果你能保证compareTo不能返回Integer.MIN_VALUE ,它的工作原理是一样的(假设compareTo方法正确实现)。

Otherwise, it would be safer to use the reverseOrder method, or to swap a and b in the expression (which is what reverseOrder does).否则,使用reverseOrder方法或在表达式中交换ab会更安全(这就是reverseOrder所做的)。

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

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