簡體   English   中英

沒有找到合適的排序方法

[英]No suitable method found for sort

我遇到了一個奇怪的 Java 編譯器問題

這是代碼

public int[] findRightInterval(int[][] intervals) {
  int n = intervals.length;
  int[] intIdx = new int[n];
  for(int i=0;i<n;i++) {
     intIdx[i]=i;
  }
  Arrays.sort(intIdx, (a, b) -> (intervals[a][0]-intervals[b][0]));
  ...
}

完整的錯誤是

Line 8: error: no suitable method found for
sort(int[],(a,b)->(in[...]][0]))
        Arrays.sort(intIdx, (a, b) -> (intervals[a][0]-intervals[b][0]));
              ^
    method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: int
        lower bounds: 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>)

另一方面,如果我替換Arrays.sort(intIdx, (a, b) -> (intervals[a][0]-intervals[b][0])); with Arrays.sort(intervals, (a, b) -> (a[0]-b[0])); 它工作正常。

想知道為什么編譯器會拋出那個錯誤?

public static <T> void Arrays.sort(T[] a, Comparator<? super T> c)

你不能用比較器對int[]數組進行排序。 只有Integer[] 因此,您的代碼段可以重寫為:

Arrays.sort(Arrays.stream(intIdx).boxed().toArray(), (a, b) -> intervals[a][0] - intervals[b][0]);

PS我建議您使用Stream作為您的示例:

intIdx = Arrays.stream(intIdx)
               .boxed()
               .sorted(Comparator.comparingInt(a -> intervals[a][0]))
               .mapToInt(i -> i)
               .toArray();

您可以導入內置類 Collections;

並寫下:Collections.sort(array);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM