Search code examples
javanodespriority-queue

Why can't I add on PriorityQueue?


I'm having troubles adding an Object Node to my PriorityQueue and I cant figure out why. When I add Node a, it has no problem.

PriorityQueue<Node> q = new PriorityQueue<Node>();
Node a = new Node('a', 1);

q.add(a);

but if I add a second Node, it throws an exception saying "java.lang.ClassCastException: Node cannot be cast to java.lang.Comparable"

PriorityQueue<Node> q = new PriorityQueue<Node>();
Node a = new Node('a', 1);
Node b = new Node('b', 2);

q.add(a);
q.add(b);

My Node class is below:

public class Node {
    public int count;
    public char character;
    public Node left;
    public Node right;

    public Node(char character, int count) {
        this(character, count, null, null);
    }

    public Node(char character, int count, Node left, Node right) {
        this.count = count;
        this.character = character;
        this.left = left;
        this.right = right;
    }

    public int compareTo(Node other) {
        return this.count - other.count;
    }
}

I guess I'm just confused why it can add Node a but not add Node b. I looked up what ClassCastException is and I dont really see that I did that kind of exception since I'm adding a type Node to a PriorityQueue of type Nodes. I would appreciate any help. Thank you!


Solution

  • The first one worked because it's the only one. From the second it needs to compare it against the first one to know where to place it on the priority queue. You need to implement the interface Comparable on your Node class and implement the compare (a, b) method. Then the Priority queue will know how to properly order the items.