我正在尝试使用 PriorityQueue 实现堆,如下所示:
PriorityQueue<Node> heap = new PriorityQueue<Node>();
Set<String> allWords = codebook.getAllWords();
for(String word : allWords)
{
heap.add(new Node(word, codebook.getProbability(word)));
System.out.println(heap.toString());
}
我将 Node 定义为包含上述方法的同一类中的私有类。节点定义为:
private static class Node implements Comparable
{
protected Node left;
protected Node right;
protected String name;
protected double frequency;
public Node(String n, double f)
{
name = n;
frequency = f;
}
public Node(double f, Node l, Node r)
{
frequency = f;
left = l;
right = r;
}
@Override
public int compareTo(Object arg0)
{
Node other = (Node)(arg0);
if(this.frequency < other.frequency)
{
System.out.println(name + " < " + other.name);
return -1;
}
else if(this.frequency > other.frequency)
{
System.out.println(name + " > " + other.name);
return 1;
}
System.out.println(name + " is equal to " + other.name);
return 0;
}
public String toString()
{return name;}
}
但是,当我将节点添加到 PriorityQueue 时,它们不是按频率排序的。根据我的 println 语句的输出,Node.compareTo() 返回了正确的值。例如,给定数据集:
- 名称、频率
- 需要,3
- 猫,1
- 整洁,2
我的代码产生:
// add need
[need]
// add cat
cat < need
[cat, need]
// 添加整洁的
整洁 > cat
[cat,need,need]
当 PriorityQueue 应该是 [cat,neat,need]
任何为什么会发生这种情况的提示?