Tim*_*oad 1 java equals priority-queue compareto
我试图使用优先级队列,但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());
Run Code Online (Sandbox Code Playgroud)
和类实现:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为输出最终输出应该是2,因为我删除了添加的'1'.compareTo()应该由优先级队列remove()使用,但他的情况似乎并非如此.我做错了什么?我知道pq.remove(a)会起作用,但我的代码也应该有用