Search code examples
javapriority-queuecomparatorcompareto

Exception in thread "main" java.lang.ClassCastException: with priority queue and comparator


What is wrong with this code. I am getting below error message.

Exception in thread "main" java.lang.ClassCastException: Nodes 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)

please help

import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

class Nodes implements Comparator<Nodes> {
        public int n;
        public int c;

        public Nodes() {
        }

        public Nodes(int n, int c) {
            this.n = n;
            this.c = c;
        }

        @Override
        public int compare(Nodes Nodes1, Nodes Nodes2) {
            if (Nodes1.c < Nodes2.c) {
                return -1;
            }
            if (Nodes1.c > Nodes2.c) {
                return 1;
            }
            return 0;
        }
    }
class dj
{ 
    public static void main(String[] args) {
Queue<Nodes> pq = new PriorityQueue<Nodes>();
    pq.add(new Nodes(5,4));
   pq.add(new Nodes(6,7));
   pq.add(new Nodes(7,6));
   pq.add(new Nodes(8,9));
   pq.add(new Nodes(9,8));
   pq.add(new Nodes(8,8));  

    }
}

Solution

  • You are getting this error because you implemented the wrong interface.

    What you need is

    class Nodes implements Comparable<Nodes>
    

    This indicates that the Nodes class can be compared to other Nodes. Which is what is required to use it in a PriorityQueue.

    A Comparator is a Class that compares Objects even if they do not implement Comparable themself. It can often be passed to specific sort functions and is usually independent of the Class itself (You can have multiple Comparator with different logic)

    See the JavaDoc of the 2 Classes for more information:

    https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
    https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html