When I try to add more than one element to a PriorityQueue in my Java class, the following exception is being thrown:
java.lang.ClassCastException
with the addition of the following message “Event cannot be cast to java.lang.Comparable
I get this expression when I’m trying to add two Event objects to the priority queue. Here’s how I initialize the priority queue etc. Maybe there’s an error in my construction of it, because it’s the first time I’m using this:
//the instance field
private PriorityQueue<Event> queue;
//Then in the constructor
queue = new PriorityQueue<Event>();
I’m just testing it out in the main method but this is when I get the above error:
public static void main(String[] args) {
SimEngine engine = new SimEngine();
Event event1 = new Event();
Event event2 = new Event();
engine.getQueue().offer(event1);
engine.getQueue().offer(event2);
System.out.println("Queue size" + engine.queue.size());
}
NOTE: I’ve tried both to invoke add and offer when trying to add to the queue. I get the same error.
All of the above code is in my SimEngine class. I know the queue needs to know how to order these elements, but I thought if you don’t specify any priority then it would just sort them naturally? Could someone please tell me what I’m doing wrong here thanks.
Eventneeds to implement theComparable<Event>interface. That means you need to write thecompareTo(Event)method. There is no “natural” ordering for objects which do not implementComparable.The other option is to pass a
Comparator<Event>implementation to the queue when the it is constructed, to tell the queue how to compareEventinstances.