LoveTW
LoveTW

Reputation: 3842

How can I delete a specific element in priority queue?

import java.util.*;

public class test4 {
  public static void main(String[] args){
    PriorityQueue[] P = new PriorityQueue[10];
    P[1] = new PriorityQueue<ClassEntry>();
    P[1].add(new ClassEntry(1.2,1));
    P[1].add(new ClassEntry(1.5,2));
    P[1].add(new ClassEntry(1.2,3));
    P[1].add(new ClassEntry(10,4));

    P[1].remove(new ClassEntry(10,4));//I can't delete this object???

    System.out.println(P[1].size());
    ClassEntry ce = (ClassEntry) P[1].peek();
    System.out.println(P[1].size());
    System.out.println(ce.sim+"\t"+ce.index);
  }
}

Why i can't delete (10,4)? Can somebody teach how to implement...thanks!

Upvotes: 5

Views: 13140

Answers (1)

rodion
rodion

Reputation: 15029

ClassEntry has to override and implement Object.equals(Object o) for remove to work. For example:

class ClassEntry{
  float a;
  int b;

  public ClassEntry(float a, int b){
    //...
  }

  @Override
  public boolean equals(Object o){
    if(o instanceof ClassEntry){
      ClassEntry c = (ClassEntry)o;
      return a == c.a && b == c.b;
    }
    return false;
  }
}

EDIT: As was kindly pointed out by @Jim Garrison, if you do not implement equals the default behaviour, which is to compare objects by reference, is used. In this case for your code to work you will need to remove like this:

PriorityQueue[] P = new PriorityQueue[10];
P[1] = new PriorityQueue<ClassEntry>();
ClassEntry entry = new ClassEntry(10,4);
P[1].add(entry);
//remove object with the same reference as the added one
P[1].remove(entry);

Upvotes: 6

Related Questions