ArrayDeque

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 than LinkedList 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 permit null 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

Use Cases

  • Stack replacement: ArrayDeque can be used as a stack (push(), pop()) but faster than Stack.
  • 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.