使用匿名比较器的ArraySort给出错误

时间:2018-08-21 12:20:47

标签: java sorting search binary comparator

错误:javac说它不适用,我不知道为什么?

plz帮助我在这里缺少什么概念

>> ROOT: }     Search_In_2D_Matrix.java:50: error: no suitable method found for sort(int[],<anonymous Comparator<Integer>>)
            Arrays.sort(arr, new Comparator<Integer>() {
                  ^
        method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
          (inference variable T#1 has incompatible bounds
            equality constraints: int
            upper bounds: Integer,Object)
        method Arrays.<T#2>sort(T#2[],int,int,Comparator<? super T#2>) is not applicable
          (cannot infer type-variable(s) T#2
            (actual and formal argument lists differ in length))
      where T#1,T#2 are type-variables:
        T#1 extends Object declared in method <T#1>sort(T#1[],Comparator<? super T#1>)
        T#2 extends Object declared in method <T#2>sort(T#2[],int,int,Comparator<? super T#2>)
    Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
    1 error

// --------------------------------------------- -----

public static void name() {
    int arr[] = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

    Arrays.binarySearch(arr, -1, new Comparator<Integer>() {
        @Override
        public int compare(Integer a, Integer b) {
            return a - b;
        }
    });

    Arrays.sort(arr, new Comparator<Integer>() {
        @Override
        public int compare(Integer a, Integer b) {
            return a.intValue() - b.intValue();
        }
    });
}

1 个答案:

答案 0 :(得分:2)

采用Comparator的方法用于对象数组。对于原始数组,您没有该选项。

您可以将int[]转换为Integer[],然后它将起作用。