2016-03-04 46 views
-3

我试图实现整数数组的自定义排序。逻辑是:通过距离查找中位数和顺序。问题是我试图使用比较器进行排序,并想知道为什么使用List的变体不起作用,而同样的Arrays.sort为我工作。Collections.sort(列表<T> t,比较器<T> c)不工作

请在下面的代码找到下面的代码,用于List变体的代码。

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; 
}`` 
+0

你有什么输出?你想要什么输出? – Tunaki

+0

由于'tempArray'是'array'的一个副本,而不是一个引用,并且该列表是从'array'而不是'tempArray'创建的,所以你正在对'tempArray'进行两次排序,但是只对列表进行一次排序。这可能不是你的实际问题,但它是一个区别,因为数组“t”已经预先排序,而列表不会。 – Thomas

+0

@Tunaki输入:{1,10,6,2,3,1,1}我期望输出:[2,1,1,1,3,6,10],但如果我使用List,{1, 10,6,2,3,1,1}比较方法的每次迭代仍然相同 –

回答

3

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

if (one == two) { 

必须

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

如果不是,你是比较引用,而不是整数的值替换.. 。

+0

或者只是'one.equals(two)'。 –

+0

谢谢...我会包括它 –

+0

感谢您的更正。但是这个代码仍然适用于Array.sort并生成正确的顺序。那么,为什么它不适用于List ... –