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?
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.
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.
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.
Answer: Yes. Priority Queue allows duplicate values.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With