【发布时间】:2021-09-23 06:02:08
【问题描述】:
我正在尝试使用 lambda 函数作为比较器在 Java 中使用自定义排序顺序对字符数组进行排序 -
order = "edcba"
char[] arr = {'a','b','c','d','e'}
我正在尝试这段代码:
Arrays.sort(arr, (a,b)->Integer.compare(order.indexOf(a), order.indexOf(b)));
但是,这给了我以下错误-
Line 4: error: no suitable method found for sort(char[],(a,b)->Int[...]f(b)))
Arrays.sort(arr, (a,b)->Integer.compare(order.indexOf(a), order.indexOf(b)));
^
method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
(inference variable T#1 has incompatible bounds
equality constraints: char
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需要Comparator<? super T> c,但你的 lambda 被推断为接受原始chars,而那些不是Objects。 -
问题是没有
Arrays.sort(char[], Comparator)方法。sort(T[], Comparator<? super T>)在这里不适用,因为T不能是char并且自动装箱在这里不起作用。您需要在此处转换为Character[]。
标签: java sorting lambda comparator