Collections.sort(List <t> t,Comparator <t> c)不起作用

时间:2016-03-04 16:31:09

标签: java sorting collections

我试图实现整数数组的自定义排序。逻辑是:找到中位数和距离的顺序。问题是我尝试使用Comparator进行排序,并且想知道为什么使用List的变体不起作用,而相同的Arrays.sort为我工作。

请在下面找到代码,评论下是用于列表变体的行。

public static Integer[] sort(Integer[] array) {
    //implement logic here
    if (array == null) return null;
    final Integer[] tempArray = Arrays.copyOf(array, array.length);
    Arrays.sort(tempArray);
    final int median = tempArray.length%2==1 ? tempArray[tempArray.length/2] : (tempArray[tempArray.length/2]+tempArray[tempArray.length/2 - 1])/2;



    //final List<Integer> t = new ArrayList(Arrays.asList(array));
    final Integer[] t = tempArray;
    //Collections.sort(t, new Comparator<Integer>()
    Arrays.sort(t, new Comparator<Integer>()
    {
        @Override
        public int compare(Integer i1, Integer i2)
        {
            Integer one = Math.abs(i1 - median);
            Integer two = Math.abs(i2 - median);
            Integer var1 = one - two;
            Integer var2 = two - one;
            System.out.println(String.format("Compare:\r\nmedian: %d\r\narg1: %d , arg2: %d\r\n"+
                    "distance1: %d, distance2: %d\r\nif dist1 > dist2 then compare: %d, else %d", median, i1, i2,one,two, var2,var1));
            System.out.println(String.format("\r\nresult: %d %s %d",i1, (one >  two?"<":one < two?">":i1.compareTo(i2)>0?">":"<"), i2));
            System.out.println("\r\n\r\nNow array is: "+Arrays.asList(t));
            System.out.println("-------------------------------");

            if (one ==  two) {
                return i1.compareTo(i2);
            } else
                return one.compareTo(two);
        }
    });

    //tempArray = (Integer[]) t.toArray(new Integer[t.size()]);

    return t;
}``

1 个答案:

答案 0 :(得分:3)

你对整数的比较是错误的......

if (one ==  two) {

必须替换为

if (one.intValue() ==  two.intValue()) {

如果没有,你是在比较参考而不是整数的值......