Some
facts about PriorityQueue
1)
PriorityQueue keeps least value element at head, where ordering
is determined using compareTo() method. It doesn't keep all elements in that
order though, only head being least value element is guaranteed. This is in
fact main difference between TreeSet and PriorityQueue in Java, former
keeps all elements in a particular sorted order, while priority queue only keeps head in sorted order.
Example
- [Watch: $200, Xbox: $300, IPone: $900, IPad: $1200]
2) PriorityQueue doesn't permit
null elements and trying to add null elements will result in NullPointerException
3) There is no
"natural" ordering for objects which do not implement Comparable. . If you don't do any of these, the queue has no way to decide if
the first element has a bigger priority than the second one.
In case of objects addition to priority queue, it must
implements Comparable interface and must override compareTo() which specify
condition which should fulfill ,where as in case of integer addition like below
, it would give result comparing with natural ordering.
public class PriorityQueueInteger {
public static void main(String[] args) {
// Priority is given by
default as natural ordering
PriorityQueue<Integer> queue= new PriorityQueue<Integer>();
queue.add(50);
queue.add(100);
queue.add(20);
queue.add(40);
System.out.println(queue);
}
}
Output : [20, 40, 50, 100]
No comments:
Post a Comment