Skip to content
Tutorials Center
My learning

Topics

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.

Java
Queue<String> line = new ArrayDeque<>();
line.offer("first");
String next = line.poll();

Try it

Java Offer, peek and poll

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.

Java Processing a work queue

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

Java
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. ArrayDeque and LinkedList are FIFO; PriorityQueue returns the smallest element first by its ordering.
  • Prefer offer/poll/peek in ordinary code. They signal "nothing there" with a value, and null is not a legal element in most queues, so there is no ambiguity.
  • Do not use null as an element. LinkedList allows it, but then poll() returning null becomes ambiguous.
  • Iteration order of for (E e : queue) follows the implementation's internal order. For PriorityQueue it is not sorted order.
  • Bounded queues exist only in java.util.concurrent (ArrayBlockingQueue, LinkedBlockingQueue with a capacity). Plain queues in java.util grow as needed.
  • For a stack too, use Deque, which adds operations at both ends.
  • Thread safety: none of the common java.util queues are synchronized; use ConcurrentLinkedQueue or a BlockingQueue between threads.