【问题标题】:Cannot infer functional interface type Error in Java无法推断 Java 中的功能接口类型错误
【发布时间】:2020-07-22 04:36:59
【问题描述】:

我正在使用 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 函数的参数,并从 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] + " ");
        }
    }
}

【问题讨论】:

  • 在评论中留下 Stacktrace

标签: java sorting functional-interface


【解决方案1】:

你可以使用

buckets[i].sort( ( Double a, Double b ) -> (int) Math.signum( a - b ) );

相反,因为DoubleComparator 接受两个Double 类型参数,而不是原始double 参数。

public int compare( Double a, Double b )

更重要的是,您可能只是希望使用Comparator.naturalOrder() 自然地对元素进行排序,因为执行减法并不是比较元素的好方法。所以你的代码看起来像 -

buckets[i].sort( Comparator.naturalOrder() );

【讨论】:

  • 我还要补充一点,在这种情况下可以使用Comparator.naturalOrder()
猜你喜欢
  • 2017-09-21
  • 1970-01-01
  • 2021-10-14
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多