Java Reference
In-Depth Information
person, who showed up after you, is served before you, based on a priority? Java also has this kind of queue and it
is called a
priority queue
. In a priority queue, you define the priority using a
Comparator
object or implement the
Comparable
interface in an element's class, and the next element in the queue to come out will be decided based on
the priority of the elements in the queue.
■
typically, a
null
element does not make sense in a
Queue
. after all, the purpose of having a queue is to apply
some processing logic on its elements or use the elements to perform some logic. in either case, a
null
value does not
make sense. it is up to the implementation of the
Queue
interface to allow or disallow
null
values. the use of
null
elements in a queue is not recommended. if you use
null
elements in a queue, you will not be able to distinguish
between the
null
value returned from its method to indicate a special situation and the
null
value of the element.
Tip
A queue lets you perform three basic operations:
•
Add an element to its tail
•
Remove an element from its head
•
The
Queue
interface defines two methods for each of the three operations. One method throws an exception if the
operation is not possible; the other method returns a value (
false
or
null
) to indicate the failure. The method you use
to perform the specific operation depends on your requirements. The
Queue
interface adds six methods to provide the
functionality of a
FIFO
queue. They are listed in Table
12-1
.
Peek the element at its head
Table 12-1.
Additional Methods Declared by the Queue Interface
Category
Method
Description
boolean add(E e)
Adding an element to the queue
Adds an element to the queue if it is possible.
Otherwise, it throws an exception.
boolean offer(E e)
Adds an element to the queue without throwing an
exception if the element cannot not be added. It
returns
false
on failure and
true
on success. It is
the preferred way to add an element in a bounded
queue.
E remove()
Removing an element from the
queue
Retrieves and removes the head of the queue.
It throws an exception if the queue is empty.
E poll()
Performs the same job as the
remove()
method.
However, it returns
null
if the queue is empty
instead of throwing an exception.
E element()
Peeking at the head of the queue
Retrieves the head of the queue without removing it
from the queue. It throws an exception if the queue
is empty.
E peek()
Performs the same job as the
element()
method.
However, it returns
null
if the queue is empty
instead of throwing an exception.