Wednesday, 21 August 2013

Java priority queues and comparable interface

Java priority queues and comparable interface

I've just been learning about priority queues thought i'd try how it
behaves with comparable interface.
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.Whats wrong.Can somebody tell me how comparable and
priority queues work.

No comments:

Post a Comment