Java Reference
In-Depth Information
«interface»
java.util.Collection<E>
«interface»
java.util.Queue<E>
«interface»
java.util.List<E>
«interface»
java.util.Deque<E>
java.util.LinkedList<E>
F IGURE 20.13
LinkedList implements List and Deque .
Listing 20.7 shows an example of using a queue to store strings. Line 4 creates a queue
using LinkedList . Four strings are added to the queue in lines 5-8. The size() method
defined in the Collection interface returns the number of elements in the queue (line
10). The remove() method retrieves and removes the element at the head of the queue
(line 11).
L ISTING 20.7
TestQueue.java
1 public class TestQueue {
2 public static void main(String[] args) {
3 java.util.Queue<String> queue = new java.util.LinkedList<>();
4 queue.offer( "Oklahoma" );
5 queue.offer( "Indiana" );
6 queue.offer( "Georgia" );
7 queue.offer( "Texas" );
8
9 while (queue.size() > 0 )
10 System.out.print(queue.remove() + " " );
11 }
12 }
creates a queue
inserts an element
queue size
remove element
Oklahoma Indiana Georgia Texas
The PriorityQueue class implements a priority queue, as shown in Figure  20.14.
By default, the priority queue orders its elements according to their natural ordering using
Comparable . The element with the least value is assigned the highest priority and thus is
removed from the queue first. If there are several elements with the same highest priority, the
tie is broken arbitrarily. You can also specify an ordering using Comparator in the construc-
tor PriorityQueue(initialCapacity, comparator) .
Listing 20.8 shows an example of using a priority queue to store strings. Line 5 creates a pri-
ority queue for strings using its no-arg constructor. This priority queue orders the strings using
their natural order, so the strings are removed from the queue in increasing order. Lines 16-17
create a priority queue using the comparator obtained from Collections.reverseOrder() ,
which orders the elements in reverse order, so the strings are removed from the queue in decreas-
ing order.
PriorityQueue class
 
 
Search WWH ::




Custom Search