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.
Deque<Integer> stack = new ArrayDeque<>(); stack.push(1); int top = stack.pop();
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 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:
pushputs the element at the front, so printing a deque used as a stack shows the newest element first. - Prefer
ArrayDequefor both stack and queue use. It is usually faster thanLinkedListand uses less memory. ChooseLinkedListonly if you neednullelements orListmethods. Stackis legacy: it is synchronized, extendsVectorand iterates bottom-up, which surprises people. PreferDeque.- Iterators:
iterator()goes head to tail,descendingIterator()tail to head. removeFirstOccurrenceandremoveLastOccurrenceremove by value usingequals, inO(n).- Java 21 added the
reversed()method throughSequencedCollection, giving a reverse-ordered view. - Not thread-safe. For concurrent use see
ConcurrentLinkedDequeorLinkedBlockingDeque.