Because TreeSet implements the NavigableSet interface (which was added by Java SE 6),
you can use the methods defined by NavigableSet to retrieve elements of a TreeSet. For
example, assuming the preceding program, the following statement uses subSet( ) to obtain a
subset of ts that contains the elements between C (inclusive) and F (exclusive). It then displays
the resulting set.
System.out.println(ts.subSet()("C", "F"));
The output from this statement is shown here:
[C, D, E]
You might want to experiment with the other methods defined by NavigableSet.
The PriorityQueue Class
PriorityQueue extends AbstractQueue and implements the Queue interface. It creates a queue
that is prioritized based on the queue's comparator. PriorityQueue is a generic class that has
this declaration:
class PriorityQueue<E>
Here, E specifies the type of objects stored in the queue. PriorityQueues are dynamic, growing
as necessary.
PriorityQueue defines the six constructors shown here:
PriorityQueue( )
PriorityQueue(int capacity)
PriorityQueue(int capacity, Comparator<? super E> comp)
PriorityQueue(Collection<? extends E> c)
PriorityQueue(PriorityQueue<? extends E> c)
PriorityQueue(SortedSet<? extends E> c)
The first constructor builds an empty queue. Its starting capacity is 11. The second constructor
builds a queue that has the specified initial capacity. The third constructor builds a queue
with the specified capacity and comparator. The last three constructors create queues that
are initialized with the elements of the collection passed in c. In all cases, the capacity grows
automatically as elements are added.
If no comparator is specified when a PriorityQueue is constructed, then the default
comparator for the type of data stored in the queue is used. The default comparator will order
the queue in ascending order. Thus, the head of the queue will be the smallest value. However,
by providing a custom comparator, you can specify a different ordering scheme. For example,
when storing items that include a time stamp, you could prioritize the queue such that the
oldest items are first in the queue.
You can obtain a reference to the comparator used by a PriorityQueue by calling its
comparator( ) method, shown here:
Comparator<? super E> comparator( )
It returns the comparator. If natural ordering is used for the invoking queue, null is returned.
One word of caution: although you can iterate through a PriorityQueue using an iterator,
the order of that iteration is undefined. To properly use a PriorityQueue, you must call methods
such as offer( ) and poll( ), which are defined by the Queue interface.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home