java - 使用匿名比较器的 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();
}
});
}
解决方案
采用 a 的方法Comparator
用于对象数组。对于原始数组,您没有该选项。
你可以把你的int[]
变成Integer[]
然后它会工作。
推荐阅读
- linux - tcpdump 不显示 Wireshark 看到的数据包
- mysql - 从 MYSQL 用户主机中删除附加的网络名称
- javascript - 关闭中的 Javascript 类库
- sql - 获取“复制”值
- docker - docker pull 完成与下载完成的区别
- php - 如何使用 php 将多页 csv 解析为 html 表
- python - 即使令牌有效,Youtube 分析 API 也会返回 403 禁止
- elixir - 将 Enum.filter 与 Enum.each 结合起来
- react-native - 反应原生 react-native-mauron85-background-geolocation:processReleaseResources FAILED
- sql - db2 存储过程中的全局临时表