[英]Cannot infer functional interface type Error in Java
我正在使用 Java 来实现桶排序。 我想对[0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434]
的输入数组进行排序,并将buckets
创建为包含List<Double>
作为元素的数组,我使用List.sort
单独对每个List<Double>
进行排序并连接它们以获得结果。
但是当我使用ArrayList.sort
方法对List
进行排序时会发生错误。 我使用 Lambda 表达式作为sort
function 的参数,并从 IDE 收到错误消息,它说Cannot infer functional interface type
。
错误来自这一行:
buckets[i].sort((double a, double b) -> (int)Math.signum(a-b));
但是当我把它改成
buckets[i].sort((a, b) -> (int)Math.signum(a-b));
没有错误,代码运行良好。
我很困惑为什么它不能推断? 提前致谢。
整个代码在这里:
import java.util.ArrayList;
import java.util.List;
class Solution {
void buckerSort(double[] arr, int n){
//create the buckets
List<Double>[] buckets = new ArrayList[n];
for (int i = 0; i<n; ++i){
buckets[i] = new ArrayList<Double>();
}
//add the input to the buckets
for (int i=0; i<n; ++i) {
int index = (int) arr[i] * 10;
buckets[index].add(arr[i]);
}
//sort every List individually
///////////////////////////////The error occurs here/////////////////////////////////////////
for (int i=0; i<n; ++i) {
buckets[i].sort((double a, double b) -> (int)Math.signum(a-b));
}
//concatenate
int index = 0;
for(int i = 0; i<n; i++) {
for (int j = 0; j<buckets[i].size(); j++) {
arr[index] = buckets[i].get(j);
index++;
}
}
}
public static void main(String args[])
{
double[] arr = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n = arr.length;
Solution s = new Solution();
s.buckerSort(arr, n);
System.out.println("Sorted array is: ");
for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " ");
}
}
}
您可以使用
buckets[i].sort( ( Double a, Double b ) -> (int) Math.signum( a - b ) );
相反,因为Double
的Comparator
器接受两个Double
类型 arguments 而不是原始double
arguments。
public int compare( Double a, Double b )
更重要的是,您可能只是希望使用Comparator.naturalOrder()
自然地对元素进行排序,因为执行减法并不是比较元素的好方法。 所以你的代码看起来像 -
buckets[i].sort( Comparator.naturalOrder() );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.