Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

The Deque interface

Reference for java.util.Deque: add and remove at both ends, use it as a stack or queue, the method families and the legacy Stack replacement.

Deque<E> (pronounced "deck") is a queue that supports insertion and removal at both ends. That makes it a single interface for three jobs: a FIFO queue, a LIFO stack, and a sliding window. The standard implementations are ArrayDeque and LinkedList.

For stacks, Deque is the recommended replacement for the legacy Stack class. Use push, pop and peek, which work at the head (front) of the deque.

Java
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
int top = stack.pop();

Try it

Java Deque as a stack and as a 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.

Java Balanced brackets and iteration directions

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 Deque<E> extends Queue<E>, SequencedCollection<E>
Operation First element (head) Last element (tail)
Insert, throwing addFirst(e) addLast(e)
Insert, special value offerFirst(e) offerLast(e)
Remove, throwing removeFirst() removeLast()
Remove, special value pollFirst() pollLast()
Examine, throwing getFirst() getLast()
Examine, special value peekFirst() peekLast()

Stack methods are aliases: push(e) is addFirst(e), pop() is removeFirst(), and peek() is peekFirst(). The queue methods add/offer act on the tail, and remove/poll on the head.

Throws: NoSuchElementException from the throwing remove/examine forms and pop() when empty; NullPointerException for null elements in ArrayDeque.

Usage notes

  • Stack order: push puts the element at the front, so printing a deque used as a stack shows the newest element first.
  • Prefer ArrayDeque for both stack and queue use. It is usually faster than LinkedList and uses less memory. Choose LinkedList only if you need null elements or List methods.
  • Stack is legacy: it is synchronized, extends Vector and iterates bottom-up, which surprises people. Prefer Deque.
  • Iterators: iterator() goes head to tail, descendingIterator() tail to head.
  • removeFirstOccurrence and removeLastOccurrence remove by value using equals, in O(n).
  • Java 21 added the reversed() method through SequencedCollection, giving a reverse-ordered view.
  • Not thread-safe. For concurrent use see ConcurrentLinkedDeque or LinkedBlockingDeque.