new ArrayDeque<>() / deque.push() / pop()
A Deque (Double Ended Queue) is a data structure that allows adding and removing elements from both ends. ArrayDeque can be used as a stack (last-in, first-out) or as a double-ended queue. Use push() and pop() for stack operations.
Syntax
// Creates an ArrayDeque. Deque<Type> dequeName = new ArrayDeque<>(); // Adds an element to the front (stack push). deque.push(element); // Removes and returns the front element (stack pop). deque.pop(); // Returns the front element without removing it. deque.peekFirst(); // Returns the last element without removing it. deque.peekLast();
Method List
| Method | Description |
|---|---|
| new ArrayDeque<>() | Creates an array-based double-ended queue. Can be used as a stack or queue. |
| push(E e) | Adds an element to the front. Equivalent to a stack push. |
| pop() | Removes and returns the front element. Equivalent to a stack pop. Throws an exception if the deque is empty. |
| peekFirst() | Returns the front element without removing it. Returns null if the deque is empty. |
| peekLast() | Returns the last element without removing it. Returns null if the deque is empty. |
Sample Code
import java.util.ArrayDeque;
import java.util.Deque;
// Used as a stack (last-in, first-out).
Deque<String> stack = new ArrayDeque<>();
stack.push("first");
stack.push("second");
stack.push("third");
System.out.println(stack.peek()); // Prints "third" (without removing).
System.out.println(stack.pop()); // Prints "third" (removes it).
System.out.println(stack.pop()); // Prints "second".
// Used as a double-ended queue.
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(1); // Adds to the front.
deque.addLast(2); // Adds to the back.
deque.addFirst(0); // Adds to the front.
System.out.println(deque.peekFirst()); // Prints "0".
System.out.println(deque.peekLast()); // Prints "2".
System.out.println(deque.pollFirst()); // Prints "0" (removes it).
System.out.println(deque.pollLast()); // Prints "2" (removes it).
Notes
When used as a stack, ArrayDeque is faster than the legacy Stack class. The Stack class extends Vector and carries synchronization overhead, so it is recommended to use ArrayDeque in single-threaded environments.
Internally, push() calls addFirst() and pop() calls removeFirst(). pop() throws a NoSuchElementException on an empty deque, so check with isEmpty() beforehand.
For queue operations (first-in, first-out), see 'new LinkedList<>() / offer() / poll() / peek()'.
If you find any errors or copyright issues, please contact us.