使用PriorityQueue删除意外行为:为什么不使用compareTo?

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)会起作用,但我的代码也应该有用

sar*_*ont 8

remove()不会使用compareTo(),而是会equals()用来找到要删除的对象.你也需要覆盖equals()你的课程.

编辑:Javadoc for PriorityQueue(Thanks,@ templatetypedef)