What is ArrayDeque in Java?

ArrayDeque in Java is a resizable array implementation of the Deque interface, which allows for the creation of a double-ended queue. It provides the functionality of adding, removing, and accessing elements from both ends of the queue, making it a versatile choice for many applications. ArrayDeque is not thread-safe, but it is faster than LinkedList for most operations due to its underlying array structure.

Some key features of ArrayDeque include:

  • Resizable: Automatically grows as needed when the queue is full.
  • Fast access: Provides O(1) time complexity for adding and removing elements from both ends.
  • Null elements not permitted: Does not allow null values for its elements.

Example of Using ArrayDeque

// Importing the ArrayDeque class import java.util.ArrayDeque; public class ArrayDequeExample { public static void main(String[] args) { // Creating an ArrayDeque ArrayDeque deque = new ArrayDeque<>(); // Adding elements deque.add("First"); deque.add("Second"); deque.addFirst("Zero"); // Adding to the front // Accessing elements System.out.println("First Element: " + deque.getFirst()); System.out.println("Last Element: " + deque.getLast()); // Removing elements deque.remove(); // Removes the first element deque.removeLast(); // Removes the last element } }

ArrayDeque Java Collections Deque Java Data Structures Java Programming