The method sort(int[]) in the type Arrays is not applicable for the arguments (int[], (<no type> o1, <no type> o2) -> {})
时间: 2024-12-04 22:22:03 浏览: 88
`sort(int[])`方法在Java的`Arrays`类中用于对整型数组进行排序,默认是采用自然排序,即将数组中的元素按照它们的自然顺序进行排列。然而,你在尝试传递一个lambda表达式作为比较器 `(int[], (<no type> o1, <no type> o2) -> {})`,这里的问题在于,`<no type>` 表明编译器无法推断`o1`和`o2`的具体类型,因此不能直接将这种函数引用作为`Comparator`的实例传递给`sort()`方法。
如果你想让`sort()`方法按降序排列,你应该提供一个实现了`Comparator`接口或者接受两个整数并返回一个负整数、零或正整数的明确比较器,而不是一个空的lambda表达式。
正确的做法可能是这样:
```java
int[] num = {5, 2, 9, 1, 7};
Arrays.sort(num, Collections.reverseOrder());
```
或者
```java
Comparator<Integer> descendingComparator = Comparator.comparingInt(o1 -> -o1);
Arrays.sort(num, descendingComparator);
```
相关问题
Line 6: error: no suitable method found for sort(int[],<anonymous Comparator<Integer>>) Arrays.sort(nums, 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 lower 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>)
这个错误的原因是`Arrays.sort`方法的第二个参数的类型不正确。`Arrays.sort`方法的第二个参数类型应该为`Comparator`,但是当前传入的是一个匿名内部类`new Comparator<Integer>() {...}`。这个匿名内部类的类型是`Comparator<Integer>`,而不是`Comparator`,因此编译器会报错。
要解决这个问题,可以将匿名内部类的类型改为`Comparator`,如下所示:
```java
Comparator<Integer> comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
Arrays.sort(nums, comparator);
```
这样就可以使用`Comparator`来指定排序规则了。
阅读全文
相关推荐














