ArrayDeque<E> · Java

push / pop (stack)

Stack operations on the head end.

public void push(E e) // addFirst; public E pop() // removeFirst

Complexity

Best caseO(1)
AmortizedO(1)
Worst caseO(n) for push when growing
Extra spaceO(1) amortized

The head index moves backwards modulo the capacity on push.

Tested example

Deque<String> stack = new ArrayDeque<>(); // preferred over the legacy Stack class
stack.push("a"); // addFirst
stack.push("b");
assert stack.pop().equals("b"); // removeFirst: last in, first out
assert stack.peek().equals("a");
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/ArrayDequeExamples.java

Parameters

e
Non-null element.

Behaviour

Returns
pop: the element most recently pushed.
Errors and preconditions
push: NullPointerException for null. pop: NoSuchElementException when empty.
Changes
Adds or removes at the head.
Memory and invalidation
push may grow the array.