Collection
operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either
null
or
false
, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted
Queue
implementations; in most implementations, insert operations cannot fail.
Throws exception | Returns special value | |
Insert | add(e) | offer(e) |
Remove | remove() | poll() |
Examine | element() | peek() |
The offer
method inserts an element if possible, otherwise returning false. This differs from the Collection.add
method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues.
The remove()
and poll()
methods remove and return the head of the queue. Exactly which element is removed from the queue is a function of the queue's ordering policy, which differs from implementation to implementation. The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null.
The element()
and peek()
methods return, but do not remove, the head of the queue.