5
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!

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

6 Comments

+1 with a clarification: the queue has to know how to determine if two objects are "equal" in order to find the one you want to delete. If you don't provide code to implement the "equal" criteria you are interested in, you get the default equals() from java.lang.Object, which compares the object addresses in memory.
thank you! but i don't know how can i let equals function works? Should i call equals() in test4 class?
equals just needs to be implemented by ClassEntry class. You don't need to call it. PriorityQueue will use it when you call remove function.
but i found that return a == o.a && b == o.b; will be error, since o is not an classEntry object? thank you:)
Actually instanceof return false if o == null, so it's not needed to check it for null. And of course you need to cast Object o to ClassEntry when you try to compare a and b variables.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.