I'm trying to implement a heap using a PriorityQueue as follows:
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());
}
Where I've defined Node as as private class inside the same class that holds the above method. Node is defined as:
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;}
}
However, when I add nodes to the PriorityQueue, they are not ordered by frequency. Based on output from my println statements, the correct values are returned by Node.compareTo(). For example, given the dataset:
- name, frequency
- need, 3
- cat, 1
- neat, 2
My code produces:
// add need
[need]
// add cat
cat < need
[cat, need]
// add neat
neat > cat
[cat, need, neat]
when the PriorityQueue should be [cat, neat, need]
Any tips as to why this is happening?