Search code examples
javacollectionsqueuepriority-queue

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


How do I get rid off this message?

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));

    }
}

Solution

  • Use non-raw PriorityQueue, and cast the result of the subtraction to int:

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

    Of course, this will give unexpected results if the difference in the longs exceeds the range of int.

    It is easier just to use:

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