0

I am trying to write a simple application with priority queues. I am getting the following errors --" error: leastPriority is not abstract and does not override abstract method compare(Integer,Integer) in Comparator" and "error: incompatible types Comparator cmp = new leastPriority(); "

Can someone point out the problem with this code.

My code is :

class leastPriority implements Comparator<Integer> {    
    public int compare(Reservation x, Reservation y){
        if(x.getPriority() > y.getPriority()){
            return -1;
        }
        if(x.getPriority() < y.getPriority()){
            return +1;
        }
        return 0;
    }
}

public class prioQueue{

    public static void main(String args[]){
        Comparator<Reservation> cmp = new leastPriority();
        PriorityQueue<Reservation> queue = new PriorityQueue<Reservation>(10,cmp);
        queue.add(new Reservation(1,"Andy",10));
        queue.add(new Reservation(1,"Peter",1));
        queue.add(new Reservation(1,"John",4));

        while(true){
            Reservation r = queue.poll();
            if(r==null){
                break;
            }
            System.out.println(r.getName());
        }

    }
}
4

2 回答 2

7

您的类型参数Comparator<T>和您的compare(T o1, T o2)方法的参数不匹配。由于在界面中它们是相同的,因此您需要为它们赋予相同的类型。

改变这个:

class leastPriority implements Comparator<Integer>

至:

class leastPriority implements Comparator<Reservation>
于 2013-05-09T15:05:24.107 回答
1

leastPriority应该实施Comparator<Reservation>而不是Comparator<Integer>. 泛型类型是在您的compare()方法中被接受为参数的类型。

PrioQueuePS 用第一个大写字母 ( ) 和 ( )命名所有 Java 类是一个好习惯LeastPriority

于 2013-05-09T15:07:02.443 回答