首页 > 解决方案 > 使用匿名比较器的 ArraySort 会出错

问题描述

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

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

>> 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();
        }
    });
}

标签: javasortingsearchbinarycomparator

解决方案


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

你可以把你的int[]变成Integer[]然后它会工作。


推荐阅读