优先队列中二元运算符“-”的错误操作数类型

bad operand types for binary operator '-' in Prioritiy Queue

如何摆脱这条消息?

bad operand types for binary operator '-'
    Queue<Long> heap = new PriorityQueue( (a,b)->b - a );
first type:  Object
second type: Object
import java.util.*; 
class solve {

    static long minCost(long arr[], int n) {
        
        Queue<Long> heap = new PriorityQueue( (a,b)-> b - a );
        
        long ans = 0;
        
        for( long i : arr )
            heap.add(i);
            
        while(!heap.isEmpty()){
            long f = heap.poll();
            
            if( heap.isEmpty()) return f+ans;
            
            long s = heap.poll();
            ans += f+s;
            heap.add(f+s);    
        }
        
        return ans;
    }
    public static void main(String[] args) {
        long a[] = {4, 3, 2, 6};
        System.out.println(minCost(a, 4));

    }
}

使用non-rawPriorityQueue,并将减法的结果转换为int

Queue<Long> heap = new PriorityQueue<>( (a,b)-> (int) (b - a) );

当然,如果多头的差异超过int的范围,这将给出意想不到的结果。

使用更简单:

Queue<Long> heap = new PriorityQueue<>(Comparator.reverseOrder());