Java Reference
In-Depth Information
Attempts to insert the given element into this queue. If the
attempt is successful,
true
is returned, otherwise
false
. For
queues that have genuine reason to reject a requestsuch as a
queue with finite capacitythis method is preferable to the
Col-
lectionadd
method which can only indicate failure by throwing
an exception.
Queues in general should not accept
null
elements because
null
is used
as a sentinel value for
poll
and
peek
to indicate an empty queue.
The
LinkedList
class provides the simplest implementation of
Queue
. For
historical reasons the
LinkedList
class accepts
null
elements, but you
should avoid inserting
null
elements when using a
LinkedList
instance
as a queue.
21.7.1.
PriorityQueue
The other
Queue
implementation is
PriorityQueue
, an unbounded queue,
based on a
priority heap.
The head of the queue is the
smallest
element
in it, where smallest is determined either by the elements' natural order
or by a supplied comparator. A
PriorityQueue
is
not
a sorted queue in the
general senseyou can't pass it to a method expecting a sorted collection-
because the iterator returned by
iterator
is
not
guaranteed to traverse
the elements in priority order; rather it guarantees that removing ele-
ments from the queue occurs in a given order. The iterator can traverse
the elements in any order. If you need ordered traversal you could ex-
tract the elements to an array and then sort the array (see "
The Arrays
Utility Class
"
on page
607
)
.
Whether the smallest element represents the element with the highest
or lowest "priority" depends on how the natural order or the comparator
is defined. For example, if queuing
Thread
objects according to their ex-
ecution priority, then the smallest element represents a
Thread
with the
lowest execution priority.
The performance characteristics of a
PriorityQueue
are unspecified. A
good
implementation
based
on
a
priority
heap
would
provide