Java Reference ยท Collections
The Queue interface
Reference for java.util.Queue: FIFO collections, the two families of methods (throwing and null-returning), common implementations and examples.
Queue<E> is the collection interface for holding elements before processing, usually in first-in, first-out (FIFO) order. You add at the tail and take from the head. LinkedList, ArrayDeque and PriorityQueue all implement it, and so do the blocking queues in java.util.concurrent.
What makes Queue unusual is that every operation comes in two forms: one that throws an exception on failure and one that returns a special value (false or null). Pick the form that fits how you want to handle an empty or full queue.
Queue<String> line = new ArrayDeque<>(); line.offer("first"); String next = line.poll();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public interface Queue<E> extends Collection<E>
| Throws an exception | Returns a special value | |
|---|---|---|
| Insert | add(e) |
offer(e) returns false if it cannot add |
| Remove | remove() |
poll() returns null if empty |
| Examine | element() |
peek() returns null if empty |
Throws: add throws IllegalStateException when a bounded queue is full. remove() and element() throw NoSuchElementException when the queue is empty. Many implementations throw NullPointerException for null elements.
Usage notes
- Order is up to the implementation.
ArrayDequeandLinkedListare FIFO;PriorityQueuereturns the smallest element first by its ordering. - Prefer
offer/poll/peekin ordinary code. They signal "nothing there" with a value, andnullis not a legal element in most queues, so there is no ambiguity. - Do not use
nullas an element.LinkedListallows it, but thenpoll()returningnullbecomes ambiguous. - Iteration order of
for (E e : queue)follows the implementation's internal order. ForPriorityQueueit is not sorted order. - Bounded queues exist only in
java.util.concurrent(ArrayBlockingQueue,LinkedBlockingQueuewith a capacity). Plain queues injava.utilgrow as needed. - For a stack too, use
Deque, which adds operations at both ends. - Thread safety: none of the common
java.utilqueues are synchronized; useConcurrentLinkedQueueor aBlockingQueuebetween threads.