简体   繁体   中英

No suitable method found for sort

I run into a strange Java compiler issue

Here is the code

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]));
  ...
}

The full error is

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>)

On the other hand, if I replace Arrays.sort(intIdx, (a, b) -> (intervals[a][0]-intervals[b][0])); with Arrays.sort(intervals, (a, b) -> (a[0]-b[0])); it works fine.

Wonder why the compiler throw that error?

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

You can't sort int[] array with comparator. Only Integer[] . So, your snippet could be rewritten with:

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

PS I reccoment you to use Stream for your example:

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

you can import the built-in class Collections;

and write this:Collections.sort(array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM