ArrayDeque
is part of Java’s java.util
package and is a class that implements the Deque
interface, which stands for “Double-Ended Queue”. Unlike a LinkedList
, an ArrayDeque
is backed by a dynamic array, making it a more efficient choice for certain types of applications. It provides a flexible structure where elements can be added or removed from both ends (front and back) with high performance.
Features
- Double-ended Queue: You can insert and remove elements from both ends of the queue (front and rear).
- No Capacity Limitation: The
ArrayDeque
dynamically grows and shrinks as needed, unlike an array with a fixed size. - Performance:
ArrayDeque
is faster thanLinkedList
for most scenarios, as it avoids the overhead of storing references to the next and previous nodes. - Not Thread-Safe:
ArrayDeque
is not synchronized, meaning it isn’t safe for concurrent use by multiple threads without external synchronization. - Does Not Allow Nulls: Unlike other collections,
ArrayDeque
does not permitnull
elements.
Common Operations
- addFirst(E e): Adds an element to the front of the deque.
- addLast(E e): Adds an element to the back of the deque.
- removeFirst(): Removes and returns the element from the front.
- removeLast(): Removes and returns the element from the back.
- peekFirst(): Retrieves, but does not remove, the element from the front.
- peekLast(): Retrieves, but does not remove, the element from the back.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.ArrayDeque; public class ArrayDequeExample { public static void main(String[] args) { // Create an ArrayDeque ArrayDeque<String> deque = new ArrayDeque<>(); // Adding elements to the deque deque.addFirst("First"); deque.addLast("Second"); deque.addFirst("Zero"); // Remove and print elements System.out.println("Removed from front: " + deque.removeFirst()); System.out.println("Removed from back: " + deque.removeLast()); // Display current elements in deque System.out.println("Deque elements: " + deque); } } |
Use Cases
- Stack replacement:
ArrayDeque
can be used as a stack (push()
,pop()
) but faster thanStack
. - Queue implementation: Acts as a queue (
offer()
,poll()
). - Sliding window problems: Common in algorithms where you need to access both ends.
- Undo/redo features: Supports adding/removing from both ends, useful in editor history.