Reputation: 9444
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());
}
}
}
Upvotes: 0
Views: 1519
Reputation: 4100
leastPriority
should implement Comparator<Reservation>
instead of Comparator<Integer>
. The generic type is the one that's accepted as a parameter in your compare()
method.
P.S. It's a good practice to name all Java classes with a first uppercase letter (PrioQueue
) and (LeastPriority
).
Upvotes: 1
Reputation: 27220
Your type parameter for Comparator<T>
and your compare(T o1, T o2)
method's parameters does not match. Since in the interface they are the same, you need to give identical types to them.
Change this:
class leastPriority implements Comparator<Integer>
to:
class leastPriority implements Comparator<Reservation>
Upvotes: 7