java 如何删除优先队列中的特定元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4543404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I delete a specific element in priority queue?
提问by LoveTW
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!
为什么我不能删除 (10,4)?有人可以教如何实施...谢谢!
采纳答案by rodion
ClassEntry
has to override and implement Object.equals(Object o)
for remove to work. For example:
ClassEntry
必须覆盖和实施Object.equals(Object o)
remove 才能工作。例如:
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:
编辑:正如@Jim Garrison 亲切指出的那样,如果您没有实现 equals,则使用默认行为,即通过引用比较对象。在这种情况下,为了让您的代码正常工作,您需要像这样删除:
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);