我正在尝试使用优先级队列,但 remove() 不起作用:我的代码:
PriorityQueue<OwnClass> pq=new PriorityQueue<OwnClass>();
OwnClass a=new OwnClass(1);
OwnClass b=new OwnClass(2);
OwnClass c=new OwnClass(3);
pq.add(a);
pq.add(b);
pq.add(c);
System.out.println("head:"+pq.peek());
pq.remove(new OwnClass(1));
System.out.println(pq.peek());
和类实现:
class OwnClass implements Comparable{
int x;
public OwnClass(int x){
this.x=x;
}
public int compareTo(Object arg0) {
OwnClass a=(OwnClass) arg0;
if(a.x>this.x)
return -1;
if(a.x<x)
return 1;
return 0;
}
public String toString(){
return ""+x;
}
}
我认为输出最终输出应该是 2,因为我要删除添加的“1”。compareTo() 应该由优先级队列 remove() 使用,但他的情况似乎并非如此。我做错了什么?我知道 pq.remove(a) 会起作用,但是我的代码也应该起作用