You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java PriorityQueue Lambda表达式返回类型不兼容错误求助

问题排查与解决

错误原因

Java中PriorityQueue的比较器(Comparator)要求lambda表达式返回int类型,你当前代码里的(p1,p2)->(p2.ratio-p1.ratio)返回的是double类型(因为ratio是double,减法结果也为double),编译器不允许这种隐式的精度损失转换,因此抛出类型不兼容的错误。

解决方法

有两种可靠的修复方式:

方法1:使用Double.compare()方法

直接调用Double.compare()比较两个double值,该方法会返回符合Comparator要求的int类型结果:

PriorityQueue<Pair> pq = new PriorityQueue<Pair>((p1, p2) -> Double.compare(p2.ratio, p1.ratio));

Double.compare(a, b)的返回规则:

  • 若a > b,返回正数
  • 若a == b,返回0
  • 若a < b,返回负数
    这里把p2.ratio放在前面,实现的是大顶堆(优先弹出ratio大的元素),完全匹配分数背包的需求。

方法2:手动判断返回int值

如果不想用工具方法,也可以手动比较后返回对应int值:

PriorityQueue<Pair> pq = new PriorityQueue<Pair>((p1, p2) -> {
    if (p2.ratio > p1.ratio) {
        return 1;
    } else if (p2.ratio < p1.ratio) {
        return -1;
    } else {
        return 0;
    }
});

这种方式逻辑更直观,同样满足Comparator的返回值要求。

修复后的完整代码

class Item {
    int value, weight;
    Item(int x, int y){
        this.value = x;
        this.weight = y;
    }
}

class Solution
{
    static class Pair {
        double ratio;
        int index;
        Pair(double rat, int ind){
            this.ratio = rat;
            this.index = ind;
        }
    }
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int W, Item arr[], int n) 
    {
        // 修复后的PriorityQueue初始化
        PriorityQueue<Pair> pq = new PriorityQueue<Pair>((p1, p2) -> Double.compare(p2.ratio, p1.ratio));
        
        for(int i=0; i<n; i++){
            double x = (arr[i].value*1.0)/(arr[i].weight*1.0);
            pq.add(new Pair(x,i));
        }
        int s=0;
        double ans=0;
        while(!pq.isEmpty()){
            Pair pair = pq.poll();
            if(s+arr[pair.index].weight <= W){ // 改为<=,避免刚好装满时进入else分支
                ans+=arr[pair.index].value;
                s+=arr[pair.index].weight;
            }else{
                double y = (W-s)*1.0;
                ans+= y*pair.ratio;
                break;
            }
        }
        return ans;
    }
}

额外补充一个小优化:原代码中的if(s+arr[pair.index].weight<W)建议改成<=,这样当剩余容量刚好等于当前物品重量时,能直接取整物品价值,逻辑更准确。

内容的提问来源于stack exchange,提问作者Hemant Srivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:06:27