简体   繁体   中英

PriorityQueue in Java

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.

Event needs to implement the Comparable<Event> interface . That means you need to write the compareTo(Event) method. There is no "natural" ordering for objects which do not implement Comparable .

The other option is to pass a Comparator<Event> implementation to the queue when the it is constructed, to tell the queue how to compare Event instances.

A PriorityQueue is a sorted collection. So the elements you add to them must be comparable with each other.

Either they must implement Comparable (and the queue sorts them using the natural ordering implied by the compareTo method), or you must provide a Comparator when creating the Queue itself (and the queue will use this comparator to compare objects and sort them).

If you don't do any of these, the queue has no way to decide if the first element has a bigger priority than the second one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM