没有找到合适的排序方法,推理数组变量具有不兼容的边界

时间:2018-04-17 13:33:36

标签: java arrays

该函数尝试将数组转换为钟形。 像输入一样:

1 3 2 5 4

答案应该是:

5 3 1 2 4

最小值介于两者之间。

public static void printPendulum(int[] arr, int n){
    Arrays.sort(arr);
    int noOfRotations = n/2;
    for(int i=0;i<noOfRotations;i++){
        int temp = arr[n-1];
        for(int j=n-1;j>0;j--){
            arr[j] = arr[j-1];
        }
        arr[0] = temp;
    }
    int temparr[] = new int[noOfRotations-1];
    for(int i=0;i<noOfRotations-1;i++)
        temparr[i] = arr[i];
    Comparator<Integer> comp = Collections.reverseOrder();     
    Arrays.sort(temparr, comp);
    for(int i=0;i<noOfRotations-1;i++)
        arr[i] = temparr[i];
    for(int i=0;i<n;i++)
        System.out.print(arr[i] + " ");
    System.out.println();     
}

编译错误如下:

    prog.java:36: error: no suitable method found for sort(int[],Comparator<Integer>)
        Arrays.sort(temparr, comp);
              ^
    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

2 个答案:

答案 0 :(得分:2)

对于基元数组,没有Comparator的签名。

例如,int[]数组的签名是:

sort(int[] a)
sort(int[] a, int fromIndex, int toIndex)

您尝试使用的那个看起来像:

sort(T[] a, Comparator<? super T> c)

所以你需要传递 Integer[] ,而不是int[]

Integer[] boxedArray = Arrays.stream(temparr).boxed().toArray(Integer[]::new);
Arrays.sort(boxedArray, comp);

答案 1 :(得分:1)

使用

Integer temparr[] = new Integer[noOfRotations-1];

代替

int temparr[] = new int[noOfRotations-1];