ArrayDeque<E> · Java
push / pop (stack)
Stack operations on the head end.
public void push(E e) // addFirst; public E pop() // removeFirst
Complexity
| Best case | O(1) |
|---|---|
| Amortized | O(1) |
| Worst case | O(n) for push when growing |
| Extra space | O(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");
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.