Java 中的错误:不兼容的类型:无法推断 PriorityQueue<>

问题描述 投票:0回答:1
class Solution {
    class City{
        int city;
        long time;
        City(int c, long t){
            city = c;
            time = t;
        }
    }
    public int countPaths(int n, int[][] roads) {
        ArrayList<ArrayList<City>> graph = new ArrayList<>();
        for(int i=0; i<n; i++)
            graph.add(new ArrayList<>());
        for(int[] road : roads){
            graph.get(road[0]).add(new City(road[1], road[2]));
            graph.get(road[1]).add(new City(road[0], road[2]));
        }
        // for(int i=0; i<n; i++){
        //     System.out.print(i+"-");
        //     for(City c : graph.get(i))
        //         System.out.print("("+c.city+","+c.time+")");
        //     System.out.println();
        // }

        PriorityQueue<City> pq= new PriorityQueue<>((a,b) -> (a.time - b.time));
        long[] times = new long[n];
        int[] ways = new int[n];
        Arrays.fill(times, Long.MAX_VALUE);
        times[0] = 0;
        ways[0] = 1;
        pq.add(new City(0, 0));
        int mod = (int) (1e9 + 7);

        while(!pq.isEmpty()){
            City c = pq.remove();
            for(City near : graph.get(c.city)){
                long cost = c.time + near.time;
                if(cost < times[near.city]){
                    times[near.city] = cost;
                    ways[near.city] = ways[c.city];
                    pq.add(new City(near.city, times[near.city]));
                }
                else if(cost == times[near.city])
                    ways[near.city] = (ways[near.city] +  ways[c.city]) % mod;
            }
        }
        //System.out.println(Arrays.toString(ways));
        return ways[n-1] % mod;
    }
}

这是错误:

Line 25: error: incompatible types: cannot infer type arguments for PriorityQueue<>
        PriorityQueue<City> pq= new PriorityQueue<>((a,b) -> (a.time - b.time));
                                                 ^
    reason: cannot infer type-variable(s) E
      (argument mismatch; bad return type in lambda expression
        possible lossy conversion from long to int)
  where E is a type-variable:
    E extends Object declared in class PriorityQueue

我尝试提供初始容量,但没有出现同样的错误。谁能告诉我为什么会发生这个错误以及如何解决它。当我将类 City 中的时间数据类型从 int 更改为 long 时,就会发生此错误。

问题出自1976年Leetcode题Number of way to meet to destination。

java graph priority-queue shortest-path
1个回答
0
投票

lambda 表达式中的返回类型错误:long 无法转换为 int

compare 方法期望返回一个 int,但您正在使用两个 long 值执行算术运算。除非您显式地将返回值转换为 int,否则它将抛出错误,因为存在有损转换(即最大的 long 值无法容纳在 int 内,如果转换为 int 将丢失信息)。

无论使用:

(a, b) -> Math.toIntExact((a.time - b.time))

(a, b) -> (int)(a.time - b.time)
© www.soinside.com 2019 - 2024. All rights reserved.