oddgamer1
oddgamer1

Reputation: 31

How do we delete an object from Priority Queue of user defined data type

class Solution{
static class pair implements Comparable<pair> {

    int a, b;

    @Override
    public int compareTo(pair o) {
        return (a-o.a);
    }

    public pair(int a, int b) {

        this.a = a;
        this.b = b;

    }

}
 public static void main(String[] args) {
        PriorityQueue<pair> min = new PriorityQueue<>();
        min.add(new pair(9,0));
        min.add(new pair(2,4));
        pair p=new pair(2, 4);
        min.remove(p);
        System.out.println(min.size());
       
       
       

    }


}

how do i delete an pair type element from priority queue. This .remove() method does not seem to work for user defined type classes.

Upvotes: 0

Views: 325

Answers (1)

woser
woser

Reputation: 11

The remove() method of the PriorityQueue implementation uses an objects equals() method to check objects for equality. The default implementation of this method checks for reference equality which isn't given in your situation. You should therefore override the equals() method in your Pair class like (or similar to) this:

@Override
public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof Pair)) {
        return false;
    }
    Pair pair = (Pair) o;
    return pair.a == a && pair.b == b;
}

For good practice you should override the hashCode() method of your Pair class as well.

Upvotes: 1

Related Questions