Java Reference
In-Depth Information
try {
String str = queue.remove();
System.out.println("queue.remove(): " + str);
}
catch (NoSuchElementException e) {
System.out.println("queue.remove(): Queue is empty.");
}
}
}
Queue: [John, Richard, Donna, Ken]
Head Element: John
Removed one element from Queue
Queue: [Richard, Donna, Ken]
Head Element: Richard
Removed one element from Queue
Queue: [Donna, Ken]
Head Element: Donna
Removed one element from Queue
Queue: [Ken]
Head Element: Ken
Removed one element from Queue
Queue: []
queue.isEmpty(): true
queue.peek(): null
queue.poll(): null
queue.element(): Queue is empty.
queue.remove(): Queue is empty.
How do you create a LIFO queue? An instance of the Stack class represents a LIFO queue. The Stack class was not
designed properly. It inherits the java.util.Vector class. You can roll out your own representation of a LIFO queue
using the LinkedList class easily. I will discuss the Deque collection interface in the next section and you will see how
to use it as a LIFO queue. You will also develop your own LIFO queue.
Priority Queues
A priory queue is a queue in which each element has an associated priority. The element with the highest priority is
removed next from the queue. Java provides PriorityQueue as an implementation class for an unbounded priority
queue. You can use natural order of the elements of the queue as its priority. In this case, the elements of the queue
must implement the Comparable interface. You can also supply a Comparator object, which will determine the priority
order of the elements. When you add a new element to a priority queue, it is positioned in the queue based on its
priority. How the priority is decided in the queue is up to you to implement.
Let's develop a priority queue based on natural ordering of its elements. Let's extend your Person class
to implement the Comparable interface. You will call your new class ComparablePerson . The priority of a
ComparablePerson will be decided on two criteria, id and name . If the id is higher, its priority is lower. If persons have
the same id , the name will be used to decide the priority based on the alphabetical order of the names. Listing 12-16
has the code for the ComparablePerson class.
 
Search WWH ::




Custom Search