Java priority queues and comparable interface

JohnnyHunter picture JohnnyHunter · Aug 21, 2013 · Viewed 19.9k times · Source

I've just been learning about priority queues and thought I'd try how it behaves with comparable interface.

Code Snippet:

import java.util.PriorityQueue;

class kinga implements Comparable<Double> {
    double time=909.909;
    double d;

    public kinga(double a) {  
        this.d=a;
    }

    public int compareTo(Double d) {
        return Double.compare(d, time);
    }

    public static void main(String arg[]) {
        PriorityQueue<kinga> r=new PriorityQueue<kinga>();

        r.add( new kinga(4545.45));
        r.add( new kinga(45.4));
        r.add( new kinga(1235.45));

        System.out.println(r.poll()+" "+r.poll()+" "+r.poll());
    }
}

It compiles but gives me Exception in thread "main" java.lang.ClassCastException: kinga cannot be cast to java.lang.Double.

What is wrong here. Can somebody tell me how comparable and priority queues work?

Answer

Katona picture Katona · Aug 21, 2013

kinga should be comparable with kinga, not Double, so:

class kinga implements Comparable<kinga>

which means your compareTo method has to be changed to this:

public int compareTo(kinga o) {
    return Double.compare(o.d, d);
}