Search code examples
javainterfacequeuecomparable

Java Comparable object with Priority Queue


I am trying to use a priority queue (java.util.PriorityQueue) on a custom class. I understand that the PriorityQueue class uses the Comparable interface, so I implemented it in my custom class:

public class State implements Comparable<State> {
    public int val;

    public State(){
        this.val = 0;
    }

    public int compareTo(State other){
        return this.val - other.val;
    }
}

And to use the queue, I did:

PriorityQueue<State> q = new PriorityQueue<State>();
q.add(myState1);
q.add(myState2);
// etc.

It compiles correctly, but I get this exception during runtime:

Exception in thread "main" java.lang.ClassCastException: State cannot be cast to
java.lang.Comparable
    at java.util.PriorityQueue.siftUpComparable(Unknown Source)
    at java.util.PriorityQueue.siftUp(Unknown Source)
    at java.util.PriorityQueue.offer(Unknown Source)
    at java.util.PriorityQueue.add(Unknown Source)
    at MapTable.search(MapTable.java:308)
    at Map.main(Map.java:67)

What am I doing wrong? As far as I can remember, this is how I would implement comparable. Thanks for all answers.


Solution

  • amit originally suggested in his comment a very wise piece of advice; essentially, make sure you're not referring to another class named State which is hiding your own State from view, e.g. java.lang.Thread.State and javax.swing.plaf.nimbus.State. This is often the cause of many bugs, so make sure you remember this.

    Unfortunately, it's not the case here. As I pointed out in a comment, the exception would print the qualified name of whatever other State as a part of the exception message in that case. Since the qualified name was State, it makes sense that you likely forgot to recompile State. :-)