PriorityQueue
- When items are added to a PriorityQueue they are not order by FIFO
- All items in a PriorityQueue must be comparable , because PriorityQueue adds and removes based on Comparable.
- A priority queue does not permit null elements.
- It does not permit insertion of non-comparable objects ; may result in ClassCastException
- Iterator does't go through elements based on priority, but you can use poll() method.
Example 1
// queue of capacity 1
PriorityQueue queue = new PriorityQueue();
// insert elements to queue
queue.offer(3.2);
queue.offer(9.8) ;
queue.offer(5.4);
System.out.print("Polling from queue: ");
// display elements in queue
while(queue.size() > 0) {
System.out.printf("%.1f ", queue.peek()); // view top element
queue.poll();
}
Output
Polling from queue: 3.2 5.4 9.8
Example 2
PriorityQueue queue = new PriorityQueue();
queue.offer("CCC-1");
queue.offer("BBB");
queue.offer("AAA");
queue.offer("CCC-2");
out.println("1. " + queue.poll()); // removes
out.println("2. " + queue.poll()); // removes
out.println("3. " + queue.peek());
out.println("4. " + queue.peek());
out.println("5. " + queue.remove()); // removes
out.println("6. " + queue.remove()); // removes
out.println("7. " + queue.peek());
out.println("8. " + queue.element()); // Throws NoSuchElementException !
Output
1. AAA
2. BBB
3. CCC-1
4. CCC-1
5. CCC-1
6. CCC-2
7. null
Exception in thread "main" java.util.NoSuchElementException
No comments:
Post a Comment
Note: only a member of this blog may post a comment.