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);
}
}
为什么我不能删除(10,4)?有人可以教会如何实施......谢谢!
答案 0 :(得分:4)
ClassEntry
必须覆盖并实施Object.equals(Object o)
才能移除工作。例如:
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;
}
}
编辑:正如@Jim Garrison所指出的,如果你没有实现等于默认行为,即使用引用来比较对象。在这种情况下,要使代码正常工作,您需要删除如下:
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);