Search code examples
javapriority-queueclasscastexceptioncomparable

PriorityQueue throwing class cast exception


PriorityQueue add method throws class cast exception (MyVertex cannot be cast to java.lang.Comparable) on executing.

Some Object of type MyVertex are inserted correctly, and some throws exception, couldn't manage to find the differences between them.

See the attached lines of code in java:

 PriorityQueue<Vertex> pq = new PriorityQueue<>();
 for (Edge edge : vertex.getEdges()) {
      pq.add(edge.getTo());
 }

expected: The method pq.add() should not throw an exception.


Solution

    1. Implement Comparable interface and override ComapareTo inside Vertex class to satisfy the priority queue's ordering.

      As the java doc says - add throws ClassCastException if the specified element cannot be compared with elements currently in this priority queue according to the priority queue's ordering.

    2. As you say it was working before, its because the add call will not throw the ClassCastException when the priorityQueues's size is 0 (when first element is added). To test that, before the call to the for loop print the size of vertex.getEdges().size(). If the size appears to be greater than 0, thats when the ClassCastException will be thrown.

    When size is not zero a sift-up operation is invoked as the underlying data_structure in the priority queue here is a heap.

    The exception that you see is triggered from sift-up, as sift-up internally requires your elements to implement Comparable. And sift-up is called when the priority queue size is not 0, or a subsequent element is added.

    Note:

    • Heap should satisfy the heap property: if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C.

      sift-up: move a node up in the tree, as long as needed; used to restore heap condition after insertion. Called "sift" because node moves up the tree until it reaches the correct level, as in a sieve.

    Heap_data_structure