Java Reference
In-Depth Information
while (pq.peek() != null) {
System.out.println("Head Element: " + pq.peek());
pq.remove();
System.out.println("Removed one element from Queue");
System.out.println("Priority queue: " + pq);
}
}
}
Priority queue: [(1, John), (3, Donna), (2, Richard), (4, Ken), (4, Adam)]
Head Element: (1, John)
Removed one element from Queue
Priority queue: [(2, Richard), (3, Donna), (4, Adam), (4, Ken)]
Head Element: (2, Richard)
Removed one element from Queue
Priority queue: [(3, Donna), (4, Ken), (4, Adam)]
Head Element: (3, Donna)
Removed one element from Queue
Priority queue: [(4, Adam), (4, Ken)]
Head Element: (4, Adam)
Removed one element from Queue
Priority queue: [(4, Ken)]
Head Element: (4, Ken)
Removed one element from Queue
Priority queue: []
There is one important thing that you will notice in the output. When you print the queue, its elements are not
ordered the way you would expect. You would expect that the element returned by the next call to the peek() method
should be at head of the queue. Note that a queue is never used to iterate over its elements. Rather, it is used to
remove one element from it, process that element, and then remove another element. The PriorityQueue class does
not guarantee any ordering of the elements when you use an iterator. Its toString() method uses its iterator to give
you the string representation of its elements. This is the reason that when we print the priority queue, its elements are
not ordered according to their priority. However, when we use the peek() or remove() method, the correct element
is peeked at or removed, which is based on the element's priority. In your case, id and name are used to order the
elements. Therefore, the element with the least id and name (alphabetical order) has the highest priority.
Using a Comparator object in a priority queue is easy. You must specify your Comparator object when you create
an object of the PriorityQueue class. Listing 12-18 demonstrates how to use a Comparator object to have a priority
queue for the list of ComparablePerson . It uses the alphabetical ordering of the name of a ComparablePerson as the
criterion to determine its priority. The person whose name comes first in the alphabetical order has higher priority.
Listing 12-18. Using a Comparator Object in a Priority Queue
// PriorityQueueComparatorTest.java
package com.jdojo.collections;
import java.util.Queue;
import java.util.PriorityQueue;
import java.util.Comparator;
public class PriorityQueueComparatorTest {
public static void main(String[] args) {
Search WWH ::




Custom Search