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.
Statein theComparable<State>is the right one, and notjava.lang.Thread.Stateorjavax.swing.plaf.nimbus.Statefor example?State.