I am trying to use the priority queue, but the remove() is not working:
My code:
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());
And the class implementation:
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;
}
}
I think the output final output should be 2, since I am removing the added ‘1’. The compareTo() should be used by priority queue remove() but his does not seem to be the case. What I am doing wrong? I know pq.remove(a) will work, but then my code should also work
remove()will not usecompareTo(), rather it will useequals()to find the object to remove. You need to overrideequals()on your class as well.Edit: Javadoc for
PriorityQueue(Thanks, @templatetypedef)