ArrayDeque Example in Java
beginner· Collections · Queue & Stack
Problem
ArrayDeque is a resizable double-ended queue — elements can be added or removed from either the front or the back, not just one end like a plain queue.
Add elements to both ends of an ArrayDeque, then remove one from each end.
Input
addFirst(10), addLast(20), addFirst(5), addLast(25)
Output
Deque: [5, 10, 20, 25]
Removed from front: 5
Removed from back: 25
Deque now: [10, 20]
Java Program
Java
import java.util.ArrayDeque;
import java.util.Deque;
public class ArrayDequeExample {
public static void main(String[] args) {
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(10);
deque.addLast(20);
deque.addFirst(5);
deque.addLast(25);
System.out.println("Deque: " + deque);
System.out.println("Removed from front: " + deque.removeFirst());
System.out.println("Removed from back: " + deque.removeLast());
System.out.println("Deque now: " + deque);
}
}Output
Deque: [5, 10, 20, 25]
Removed from front: 5
Removed from back: 25
Deque now: [10, 20]
Core Logic
Calling addFirst() and addLast() in whatever order builds up the deque from both directions at once, and the same first/last symmetry applies when removing elements again.
How It Works
- 1
addFirst(10)starts the deque with a single element. - 2
addLast(20)appends to the opposite end, thenaddFirst(5)andaddLast(25)keep extending both ends, ending with[5, 10, 20, 25]. - 3
removeFirst()removes and returns the element currently at the front —5. - 4
removeLast()removes and returns the element currently at the back —25— leaving[10, 20].
Building the deque from both ends produces
[5, 10, 20, 25], and removing one element from each end brings it back down to [10, 20].💡
Key Point: Every one of these four methods works on a specific end — there's no ambiguity about which side is affected, unlike a plain List where add() always appends to the end.
Complexity
Time Complexity: O(1)Space Complexity: O(n)
Why: ArrayDeque's resizable circular array lets it add or remove from either end in amortized constant time, while holding up to n elements at once.
Key Concepts
ArrayDequeaddFirst()addLast()removeFirst()removeLast()