Lov*_*eTW 4 java 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);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能删除 (10,4)?有人可以教如何实施...谢谢!
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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如@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);
Run Code Online (Sandbox Code Playgroud)