Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java priority queues and comparable interface

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?

like image 896
JohnnyHunter Avatar asked Aug 21 '13 11:08

JohnnyHunter


People also ask

What is comparable interface in Java?

The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java. lang.

Does Java have a priority queue?

Priority queues with natural ordering PriorityQueue is available in java. util package. Since we did not tell the priority queue how to prioritize its content, it used a default natural ordering. In this case, it gave us the data back in the ascending order of the strings.

How do you compare priority queues?

In a priority queue, an element with high priority is served before an element with low priority. For this, it uses a comparison function which imposes a total ordering of the elements.

Does priority queue allow duplicates Java?

Answer: Yes. Priority Queue allows duplicate values.


1 Answers

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);
}
like image 94
Katona Avatar answered Nov 26 '22 23:11

Katona