想实现整数数组从大到小排序,使用Comparator,写了如下代码,为什么编译不通过啊,那里有问题?
[code]
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
int[] a = {1,6,3,7,2,9};
Arrays.sort(a, new Cmp());
}
}
class Cmp implements Comparator<Integer> { public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}[/code]

解决方案 »

  1.   

    Arrays.sort函数有接受int和Comparator的版本吗?好像没有吧,只有:
    static void sort(int[] a) 
    static void sort(int[] a, int fromIndex, int toIndex)
      

  2.   

    sort
    public static <T> void sort(T[] a,
                                Comparator<? super T> c)
    Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the array).
    This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance. 
    Parameters:
    a - the array to be sorted.
    c - the comparator to determine the order of the array. A null value indicates that the elements' natural ordering should be used. 
    Throws: 
    ClassCastException - if the array contains elements that are not mutually comparable using the specified comparator.
    See Also:
    Comparator
      

  3.   

    import java.util.Arrays;
    import java.util.Comparator;
    public class Test {
    public static void main(String[] args) {
    Integer[] a = {1,6,3,7,2,9};
    Arrays.sort(a, new Cmp());
                      for(int i=0;i<a.length;i++)
    {
    System.out.println(a[i]);
    }
    }
    }
    class Cmp implements Comparator<Integer> { public int compare(Integer o1, Integer o2) {
             int i=o2-o1;
    if(i>0)
    return 1;
    if(i<0)
    return -1;
    else
    return 0;
    }
    }
      

  4.   

    必须得是Integer型数组吗?如果传进来的参数是int型数组,想实现从大到小排序怎么办?(最好不要先从小到大排再倒置)
      

  5.   

    用int数组的时候,编译器分析该用哪个重载时可能会分析不到“public static <T> void sort(T[] a, Comparator<? super T> c)”的头上。
    当然,当非范型函数遭遇范型函数,内建类型数组遭遇自定义类型数组,具体编译器会怎么处理偶也没钻研过,说不上来了。但有一点是肯定的,即便那样可以,你用int[]的效率也不太会比Integer[]高,因为前者在排序的过程中,在每一步调用Comparator的compare的时候,都要对两个参数各进行一个装箱,然后,从compare返回,再来一次拆箱
      

  6.   


    //随第一个参数小于、等于或大于第二个参数而分别返回负整数、零或正整数
    无非就是重载那个int compare(对象1,对象2)的时候返回值改一下就好了。