Queues – Collections: Part II
By Jaime Williams / August 23, 2022 / No Comments / Introduction to Streams, Oracle Certification Exam
15.6 Queues
In this section we look at the different types of queues provided by the Java Collections Framework.
The Queue<E> Interface
The Queue<E> interface extends the Collection<E> interface to specify a general contract for queues. A queue is a collection that maintains elements in processing order. An implementation of the Queue<E> interface provides the queue policy for yielding the next element for processing. A head position in the queue specifies where the next element for processing can be obtained. A basic queue usually maintains its elements in FIFO (first in, first out) ordering, but other orderings are also quite common: LIFO (last in, first out) ordering (also called stacks) and priority ordering (also called priority queues). The order in which elements of a queue can be retrieved for processing is dictated either by the natural ordering of the elements or by a comparator. A queue can be unbounded or capacity-restricted, depending on its implementation.
The Queue<E> interface extends the Collection<E> interface with the following methods. A summary of these methods is presented in Table 15.4.
Table 15.4 Summary of Methods in the Queue Interface
Operation | Throws exception | Returns special value |
Insert at the tail | add(e) can throw IllegalArgumentException | offer(e) returns true or false |
Remove from the head | remove() can throw NoSuchElementException | poll() returns head element or null |
Examine element at the head | element() can throw NoSuchElementException | peek() returns head element or null |
// Insert
boolean add(E element)
boolean offer(E element)
Both methods insert the specified element in the queue. The return value indicates the success or failure of the operation. The add() method inherited from the Collection<E> interface throws an IllegalStateException if the queue is full, but the offer() method does not.
// Remove
E remove()
E poll()
Both methods retrieve the head element and remove it from the queue. If the queue is empty, the remove() method throws a NoSuchElementException, but the poll() method returns the null value.
// Examine
E element()
E peek()
Both methods retrieve the head element, but do not remove it from the queue. If the queue is empty, the element() method throws a NoSuchElementException, but the peek() method returns the null value.