[英]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.