Open In App

ArrayDeque in Java

Last Updated : 14 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Java, the ArrayDeque is a resizable array implementation of the Deque interface, which stands for double-ended queue. It allows elements to be added or removed from both ends efficiently. It can be used as a stack (LIFO) or a queue (FIFO).

  • ArrayDeque grows dynamically.
  • It generally provides faster operations than LinkedList because it does not have the overhead of node management.
  • Operations like addFirst(), addLast(), removeFirst(), removeLast() are all done in constant time O(1).
  • The ArrayDeque class implements these two interfaces Queue interface and Deque interface. support concurrent access by multiple threads.

Example: This example demonstrates how to use an ArrayDeque to add elements to both ends of the deque and then remove them from both ends using addFirst(), addLast(), removeFirst(), and removeLast() methods.

// Java Program to demonstrates 
// the working of ArrayDeque
import java.util.ArrayDeque;
import java.util.Deque;

public class Geeks {
    
    public static void main(String[] args) {
        
        Deque<Integer> d = new ArrayDeque<>();
        d.addFirst(1);
        d.addLast(2);
        int f = d.removeFirst();
        int l = d.removeLast();
        System.out.println("First: " + f + ", Last: " + l);
    }
}

Output
First: 1, Last: 2

ArrayDeque Hierarchy

The below image demonstrates the inheritance hierarchy of ArrayDeque, how it implements the Deque interface, which extends the Queue , and how both are part of the Collection interface.

ArrayDeque


Declaration of ArrayDeque

In Java, the declaration of ArrayDeque can be done as:

ArrayDeque<Type> deque = new ArrayDeque<>();

Note: Here, “Type” is the type of the element the deque will hold (e.g. Integer, String).

Constructors

Constructor

Description

ArrayDeque()

This constructor is used to create an empty ArrayDeque and by default holds an initial capacity to hold 16 elements

ArrayDeque(Collection<? extends E> c)

This constructor is used to create an ArrayDeque containing all the elements the same as that of the specified collection.

ArrayDeque(int numofElements)

This constructor is used to create an empty ArrayDeque and holds the capacity to contain a specified number of elements


Example 1: This example demonstrates how to create an empty ArrayDeque, add elements to it, and print the deque’s contents.

// Java Program to demonstrates 
// the working of ArrayDeque()
import java.util.ArrayDeque;

public class Geeks {
    public static void main(String[] args) {
        
        // Empty d with default capacity
        ArrayDeque<Integer> d = new ArrayDeque<>(); 
        d.add(10);
        d.add(20);
        System.out.println("ArrayDeque: " + d);  
    }
}

Output
ArrayDeque: [10, 20]


Example 2: This example demonstrates how to initialize an ArrayDeque with elements from a collection and print its contents.

// Java Program to demonstrates the working of
// ArrayDeque(Collection<? extends E> c)
import java.util.ArrayDeque;
import java.util.Arrays;

public class Geeks {
    public static void main(String[] args)
    {
        ArrayDeque<Integer> d
            = new ArrayDeque<>(Arrays.asList(1, 2, 3, 4));
        System.out.println("ArrayDeque: " + d);
    }
}

Output
ArrayDeque: [1, 2, 3, 4]


Example 3: This example demonstrates how to create an ArrayDeque with a specified initial capacity (10) and add elements to it.

// Java Program to demonstrates the working of
// ArrayDeque(int numofElements)
import java.util.ArrayDeque;

public class Geeks {
    public static void main(String[] args)
    {
        ArrayDeque<Integer> d = new ArrayDeque<>(10);
        d.add(5);
        d.add(15);
        System.out.println("ArrayDeque: " + d);
    }
}

Output
ArrayDeque: [5, 15]

Performing Various Operations on ArrayDeque

1. Adding Element: We can use methods like add(), addFirst(), addLast(), offer(), offerFirst(), offerLast() to insert element to the ArrayDeque.

Example: This example demonstrates how to use various methods add(), addFirst(), addLast(), offer(), offerFirst(), offerLast() to insert elements in the Deque.

// Java program to demonstrates 
// Addition of elements in ArrayDeque
import java.io.*;
import java.util.*;
public class Geeks {

    public static void main(String[] args)
    {
        // Initializing a deque
        // since deque is an interface
        // it is assigned the
        // ArrayDeque class
        Deque<String> d = new ArrayDeque<String>();

        // add() method to insert
        d.add("The");
        d.addFirst("To");
        d.addLast("Geeks");

        // offer() method to insert
        d.offer("For");
        d.offerFirst("Welcome");
        d.offerLast("Geeks");

        System.out.println("ArrayDeque : " + d);
    }
}

Output
ArrayDeque : [Welcome, To, The, Geeks, For, Geeks]


2. Accessing Elements: We can use methods like getFirst(), getLast(), peek(), peekFirst(), peekLast() to access elements of the ArrayDeque.

Example: This example demonstrates how to access the elements of the ArrayDeque using getFirst() and getLast() method.

// Java program to Access Elements of ArrayDeque
import java.io.*;
import java.util.*;
public class Geeks {

    public static void main(String args[])
    {
        // Creating an empty ArrayDeque
        ArrayDeque<String> d
                = new ArrayDeque<String>();

        // Using add() method to add elements into the Deque
        // Custom input elements
        d.add("Welcome");
        d.add("To");
        d.add("Geeks");
        d.add("for");
        d.add("Geeks");

        // Displaying the ArrayDeque
        System.out.println("ArrayDeque: " + d);

        // Displaying the First element
        System.out.println("The first element is: "
                + d.getFirst());

        // Displaying the Last element
        System.out.println("The last element is: "
                + d.getLast());
    }
}

Output
ArrayDeque: [Welcome, To, Geeks, for, Geeks]
The first element is: Welcome
The last element is: Geeks


3. Removing Elements: We can use various methods like remove(), removeFirst(), removeLast(), poll(), pollFirst(), pollLast(), pop() to remove elements from the ArrayDeque.

Example: This example demonstrates removing elements from the ArrayDeque using pop(), poll() and pollFirst() method.

// Java program to demomstrates 
// Removal Elements in Deque
import java.util.*;
public class Geeks {
    public static void main(String[] args) {
        
        // Initializing a deque
        Deque<String> d = new ArrayDeque<String>();

        // Adding elements
        d.add("Java");
        d.addFirst("C++");
        d.addLast("Python");

        // Printing initial elements
        System.out.println("Initial Deque: " + d);

        // Removing elements as a stack from top/front
        System.out.println("Removed element using pop(): " + d.pop());

        // Removing an element from the front
        System.out.println("Removed element using poll(): " + d.poll());

        // Removing an element from the front using pollFirst
        System.out.println("Removed element using pollFirst(): " + d.pollFirst());

        // The deque is empty now
        System.out.println("Final Deque: " + d);
    }
}

Output
Initial Deque: [C++, Java, Python]
Removed element using pop(): C++
Removed element using poll(): Java
Removed element using pollFirst(): Python
Final Deque: []


4.Iterating Elements: We can use various methods like remove(), iterator(), descendingIterator() to iterate over the elements of ArrayDeque.

Example: This example demonstrates iterating through a Deque in both forward and reverse order using the Iterator and descendingIterator() method.

// Java program to Illustrate 
// Iteration of Elements in Deque
import java.util.*;
public class Geeks {
    public static void main(String[] args)
    {
        // Declaring and initializing an deque
        Deque<String> d = new ArrayDeque<String>();

        // Adding elements at the back
        // using add() method
        d.add("For");

        // Adding element at the front
        // using addFirst() method
        d.addFirst("Geeks");

        // add element at the last
        // using addLast() method
        d.addLast("Geeks");
        d.add("is so good");

        // Iterate using Iterator interface
        // from the front of the queue
        System.out.println("Iterating in ForwardOrder:");
        for (Iterator i = d.iterator(); i.hasNext();) {

            // Print the elements
            System.out.print(i.next() + " ");
        }

        // New line
        System.out.println();

        // Iterate in reverse sequence in a queue
        System.out.println("Iterating in ReverseOrder:");
        for (Iterator i = d.descendingIterator();
             i.hasNext();) {

            System.out.print(i.next() + " ");
        }
    }
}

Output
Iterating in ForwardOrder:
Geeks For Geeks is so good 
Iterating in ReverseOrder:
is so good Geeks For Geeks 

Methods

Method

Description

add(Element e)The method inserts a particular element at the end of the deque.
addAll​(Collection<? extends E> c)Adds all of the elements in the specified collection at the end of this deque, as if by calling addLast(E) on each one, in the order that they are returned by the collection’s iterator.
addFirst(Element e)The method inserts particular element at the start of the deque.
addLast(Element e) The method inserts a particular element at the end of the deque. It is similar to the add() method
clear() The method removes all deque elements.
clone()The method copies the deque.
contains(Obj)The method checks whether a deque contains the element or not
element() The method returns element at the head of the deque
forEach​(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
getFirst()The method returns first element of the deque
getLast()The method returns last element of the deque
isEmpty()The method checks whether the deque is empty or not.
iterator()Returns an iterator over the elements in this deque.
offer(Element e)The method inserts element at the end of deque.
offerFirst(Element e) The method inserts element at the front of deque.
offerLast(Element e)The method inserts element at the end of the deque.
peek()The method returns head element without removing it.
poll()The method returns head element and also removes it
pop()The method pops out an element for stack represented by deque
push(Element e)The method pushes an element onto stack represented by deque
remove()The method returns head element and also removes it
remove​(Object o)Removes a single instance of the specified element from this deque.
removeAll​(Collection<?> c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
removeFirst()The method returns the first element and also removes it
removeFirstOccurrence​(Object o)Removes the first occurrence of the specified element in this deque (when traversing the deque from head to tail).
removeIf​(Predicate<? super Element> filter)Removes all of the elements of this collection that satisfy the given predicate.
removeLast()The method returns the last element and also removes it
removeLastOccurrence​(Object o)Removes the last occurrence of the specified element in this deque (when traversing the deque from head to tail).
retainAll​(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
size()Returns the number of elements in this deque.
spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this deque.
toArray()Returns an array containing all of the elements in this deque in proper sequence (from first to the last element).
toArray​(T[] a)Returns an array containing all of the elements in this deque in proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array.

Methods Inherited from Class java.util.AbstractCollection

Method 

Action Performed 

containsAll(Collection c)Returns true if this collection contains all of the elements in the specified collection.
toString()Returns a string representation of this collection.

Methods Inherited from Interface java.util.Collection

Method 

Action Performed 

containsAll(Collection c)Returns true if this collection contains all of the elements in the specified collection.
equals()Compares the specified object with this collection for equality.
hashcode()Returns the hash code value for this collection.
parallelStream()Returns a possibly parallel Stream with this collection as its source.
stream()Returns a sequential Stream with this collection as its source.
toArray​(IntFunction<T[]> generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Methods Declared in Interface java.util.Deque

Method 

Action Performed 

descendingIterator()Returns an iterator over the elements in this deque in reverse sequential order.
peekFirst()Retrieves, but does not remove, the first element of this deque, or returns null if this deque is empty.
peekLast()Retrieves, but does not remove, the last element of this deque, or returns null if this deque is empty.
pollFirst()Retrieves and removes the first element of this deque, or returns null if this deque is empty.
pollLast()Retrieves and removes the last element of this deque, or returns null if this deque is empty.

Advantages

  • The ArrayDeque class provides constant-time performance for inserting and removing elements from both ends of the queue, making it a good choice for scenarios where you need to perform many add and remove operations.
  • The ArrayDeque class uses a resizable array to store its elements, which means that it can grow and shrink dynamically to accommodate the number of elements in the queue.
  • The ArrayDeque class is a lightweight data structure that does not require additional overhead, such as linked list nodes, making it a good choice for scenarios where memory is limited.
  • The ArrayDeque class is not thread-safe, but you can use the Collections.synchronizedDeque method to create a thread-safe version of the ArrayDeque class.

Disadvantages

  • By default, the ArrayDeque class is not synchronized, which means that multiple threads can access it simultaneously, leading to potential data corruption.
  • Although the ArrayDeque class uses a resizable array to store its elements, it still has a limited capacity, which means that you may need to create a new ArrayDeque when the old one reaches its maximum size.


Similar Reads

three90RightbarBannerImg