Collections.sort不能用于自定义比较器?

时间:2011-06-29 14:12:59

标签: java sorting collections comparator

import java.util.*;

public class ABC {
    public static void main(String[] args) {
        List<Integer> values = null;

        values = new ArrayList<Integer>();
        values.add(5);
        values.add(9);
        values.add(3);
        values.add(55);
        values.add(4);

        Collections.sort(values);
        System.out.println(values);



        values = new ArrayList<Integer>();
        values.add(5);
        values.add(9);
        values.add(3);
        values.add(55);
        values.add(4);

        Comparator<Integer> cmp = new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        int o1i = o1;
                        int o2i = o2;
                        return o1i - o1i;
                    }
                };

        Collections.sort(values, cmp);
        System.out.println(values);
    }
}

打印:

[3, 4, 5, 9, 55]
[5, 9, 3, 55, 4]

这显然不是预期的结果。我错过了什么?

5 个答案:

答案 0 :(得分:7)

你有一个错误:

更改

return o1i - o1i;

return o1i - o2i;

答案 1 :(得分:2)

你的比较器正在减去o1i - o1i,每次给你0。

(通过将o1o2分配给本地int变量,您无法获得任何收益;只需减去o1 - o2。)

答案 2 :(得分:1)

您输入错误,comperator应该有return o1i - o2i;

而不是return o1i - o1i;

答案 3 :(得分:0)

return o1i - o1i;

我猜你的意思;

return o1i - o2i;

答案 4 :(得分:0)

使用这个

int o1i = o1;
                    int o2i = o2;
                    return o1i - o2i;

这给出了以下结果

[3, 4, 5, 9, 55]

[3,4,5,9,55]

相关问题