开发者

Collections.sort won't work with custom comparator?

import java.util.*;

public class ABC {
    public static void main(String[] ar开发者_运维知识库gs) {
        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);
    }
}

This prints:

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

which is obviously not the expected result. What am I missing?


You have a bug:

Change

return o1i - o1i;

to

return o1i - o2i;


Your comparator is subtracting o1i - o1i, giving you 0 each time.

(You aren't gaining anything by assigning o1 and o2 to local int variables either; just subtract o1 - o2.)


You have a typing error, the comperator should have return o1i - o2i;

and not return o1i - o1i;


return o1i - o1i;

I guess you meant;

return o1i - o2i;


use this one

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

This gives following result

[3, 4, 5, 9, 55]

[3, 4, 5, 9, 55]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜