Table of contents
1.
Introduction
2.
Hierarchy of ArrayDeque Class in Java
3.
Interfaces Implemented by ArrayDeque
4.
Java ArrayDeque Class Constructors
5.
Methods of ArrayDeque in Java
6.
Examples of ArrayDeque Class
6.1.
1. Addition of Elements
6.2.
Java
6.3.
2. Accessing the Elements
6.4.
Java
6.5.
3. Removing Elements
6.6.
Java
6.7.
4. Iterating through the Deque
6.8.
Java
6.9.
5. ArrayDeque as a Stack
6.10.
Java
7.
Advantages of Using ArrayDeque
8.
Disadvantages of Using ArrayDeque
9.
Frequently Asked Questions
9.1.
What is the difference between Deque and ArrayDeque?
9.2.
Can we add null in ArrayDeque?
9.3.
Does ArrayDeque implement list?
9.4.
Is ArrayDeque better than stack?
9.5.
What is the difference between ArrayDeque and ArrayList?
10.
Conclusion
Last Updated: Dec 2, 2024
Easy

ArrayDeque in Java

Author Sanjana Yadav
0 upvote

Introduction

ArrayDeque in Java provides a mechanism to use resizable-array in addition to the Deque interface implementation. It's also known as Array Deck or Array Double Ended Queue. This is a unique type of array that allows users to add or delete elements from both sides of the queue.

ArrayDeque is very useful for implementing stacks and queues whose sizes are not known in advance since it has no capacity limits.

ArrayDeque in Java

Unlike ArrayList, ArrayDeque is not limited to resizing only at the end; it can resize at both ends, making it more efficient for certain operations. It does not allow null elements and is not thread-safe unless guarded by external synchronization.

Hierarchy of ArrayDeque Class in Java

The Java Deque interface extends the Queue interface to provide double-ended queues. It is implemented by the LinkedList and ArrayDeque classes, which may both be used to form a queue whose size can be increased as needed.

Java LinkedList is appropriate for queue operations because it is efficient for adding and deleting elements from both ends of a list.

ConcurrentLinkedDeque and LinkedBlockingDeque are two other implementation classes that implement the deque interface.

Interfaces Implemented by ArrayDeque

The ArrayDeque class implements these two interfaces:

Queue Interface: The components are inserted from the rear of the queue interface, which is a FirstIn – FirstOut Data Structure.

Deque Interface: This is a Double-Ended Queue in which components can be inserted from both sides. It is a Queue implementation interface.

Java ArrayDeque Class Constructors

The constructors defined by the ArrayDeque class are as follows: 

ConstructorDescription
ArrayDeque()Constructs an empty deque with an initial capacity of 16.
ArrayDeque(int initialCapacity)Constructs an empty deque with the specified initial capacity.
ArrayDeque(Collection<? extends E> c)Constructs a deque containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Methods of ArrayDeque in Java

In Java, ArrayDeque introduces no new methods. All the methods are inherited by Deque, Queue, and Collection interface. The following are the most important methods:

MethodDescription
add(E e)Adds the specified element to the end of the deque.
addFirst(E e)Inserts the specified element at the front of the deque.
addLast(E e)Inserts the specified element at the end of the deque.
offer(E e)Adds the specified element to the end of the deque if it is possible to do so immediately without violating capacity restrictions.
offerFirst(E e)Inserts the specified element at the front of the deque unless it would violate capacity restrictions.
offerLast(E e)Inserts the specified element at the end of the deque unless it would violate capacity restrictions.
remove()Retrieves and removes the first element of the deque.
removeFirst()Retrieves and removes the first element of the deque.
removeLast()Retrieves and removes the last element of the deque.
poll()Retrieves and removes the first element of the deque, or returns null if the deque is empty.
pollFirst()Retrieves and removes the first element of the deque, or returns null if the deque is empty.
pollLast()Retrieves and removes the last element of the deque, or returns null if the deque is empty.
element()Retrieves, but does not remove, the first element of the deque.
getFirst()Retrieves, but does not remove, the first element of the deque.
getLast()Retrieves, but does not remove, the last element of the deque.
peek()Retrieves, but does not remove, the first element of the deque, or returns null if the deque is empty.
peekFirst()Retrieves, but does not remove, the first element of the deque, or returns null if the deque is empty.
peekLast()Retrieves, but does not remove, the last element of the deque, or returns null if the deque is empty.
size()Returns the number of elements in the deque.
isEmpty()Returns true if the deque contains no elements.
iterator()Returns an iterator over the elements in the deque.
descendingIterator()Returns an iterator over the elements in the deque, in reverse sequential order.
toArray()Returns an array containing all of the elements in the deque, in the same order as they are returned by the iterator.
toArray(T[] a)Returns an array containing all of the elements in the deque, in the same order as they are returned by the iterator; the runtime type of the returned array is that of the specified array.
clear()Removes all of the elements from the deque.
contains(Object o)Returns true if the deque contains the specified element.
remove(Object o)Removes the first occurrence of the specified element from the deque.
addAll(Collection<? extends E> c)Adds all of the elements in the specified collection to the end of the deque.
removeFirstOccurrence(Object o)Removes the first occurrence of the specified element from the deque.
removeLastOccurrence(Object o)Removes the last occurrence of the specified element from the deque.
addAll(int index, Collection<? extends E> c)Adds all of the elements in the specified collection into this deque at the specified position.
equals(Object o)Compares the specified object with this deque for equality.
hashCode()Returns the hash code value for this deque.
spliterator()Creates a late-binding and fail-fast Spliterator over the elements in the deque.

Also see,  Swap Function in Java

Examples of ArrayDeque Class

1. Addition of Elements

Let's write a programme that adds items to the ArrayDeque using methods like add(), addFirst(), addLast(), offer(), offerFirst(), offerLast(), and offerLast().

Example

  • Java

Java

import java.util.ArrayDeque;
public class SampleArrayDeque {
public static void main(String[] args)
{
// Create object of ArrayDeque class of String type. 
 ArrayDeque<Integer> dq = new ArrayDeque<Integer>();


// Adding elements to deque using add() method.
   dq.add(30);
   dq.addFirst(50);
   dq.addLast(07);


// Adding elements to deque using offer() method. 
   dq.offer(60);
   dq.offerFirst(80);
   dq.offerLast(70);


System.out.println("Elements in ArrayDeque are : " + dq);
}
}
You can also try this code with Online Java Compiler
Run Code

Output

Elements in ArrayDeque are : [80, 50, 30, 7, 60, 70]


Practice by yourself on online java compiler.

2. Accessing the Elements

Let's write a program that uses methods like getFirst(), getLast(), and so on to access items.

Example

  • Java

Java

import java.util.ArrayDeque;
public class SampleArrayDeque {
   public static void main(String[] args) {
       ArrayDeque<String> flowers= new ArrayDeque<>();
       
       flowers.add("Sunflower");
       flowers.add("Rose");
       flowers.add("Lily");
       System.out.println("ArrayDeque: " + flowers);
       
       // Get the first element
       String firstElement = flowers.getFirst();
       System.out.println("First Element: " + firstElement);
       
       // Get the last element
       String lastElement = flowers.getLast();
       System.out.println("Last Element: " + lastElement);
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

ArrayDeque: [Sunflower, Rose, Lily]
First Element: Sunflower
Last Element: Lily

3. Removing Elements

Let's write a program that removes an element from a deque using various methods such as removeFirst(), removeLast(), poll(), pop(), pollFirst(), pollLast().

Example

  • Java

Java

import java.util.ArrayDeque;
public class  SampleArrayDeque{
   public static void main(String[] args) {
       ArrayDeque<String> Elements= new ArrayDeque<>();
       Elements.add("Element1");
       Elements.add("Element2");
       Elements.add("Element3");
       Elements.add("Element4");
       System.out.println("ArrayDeque: " + Elements);

       // Using remove()
       String element = Elements.remove();
       System.out.println("Removed Element: " + element);

       System.out.println("New ArrayDeque: " + Elements);
       // Using removeFirst()
       String firstElement = Elements.removeFirst();
       System.out.println("Removed First Element: " + firstElement);


       // Using removeLast()
       String lastElement = Elements.removeLast();
       System.out.println("Removed Last Element: " + lastElement);
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

ArrayDeque: [Element1, Element2, Element3, Element4]
Removed Element: Element1
New ArrayDeque: [Element2, Element3, Element4]
Removed First Element: Element2
Removed Last Element: Element4

4. Iterating through the Deque

ArrayDeque's iterator() and descendingIterator() methods may loop through elements from both ends of the deque. Take a look at the raw code below.

Example

  • Java

Java

import java.util.ArrayDeque;
import java.util.Iterator;
public class  SampleArrayDeque {
   public static void main(String[] args) {
       ArrayDeque<String> numbers= new ArrayDeque<>();
       numbers.add("One");
       numbers.add("Two");
       numbers.add("Three");

       System.out.print("ArrayDeque: ");

       // Using iterator()
       Iterator<String> iterate = numbers.iterator();
       while(iterate.hasNext()) {
           System.out.print(iterate.next());
           System.out.print(", ");
       }

       System.out.print("\nArrayDeque in reverse order: ");
       // Using descendingIterator()
       Iterator<String> desIterate = numbers.descendingIterator();
       while(desIterate.hasNext()) {
           System.out.print(desIterate.next());
           System.out.print(", ");
       }
   }
}
You can also try this code with Online Java Compiler
Run Code


Output

ArrayDeque: One, Two, Three,
ArrayDeque in reverse order: Three, Two, One,

5. ArrayDeque as a Stack

It is advised to use a deque over the Stack class to implement LIFO (Last-In-First-Out) stacks in Java. The ArrayDeque class will almost certainly be faster than the Stack class.

ArrayDeque provides methods like push(), peek(), pop() for implementing a stack.

Example

  • Java

Java

import java.util.ArrayDeque;

public class  SampleArrayDeque {
   public static void main(String[] args) {
       ArrayDeque<String> stack = new ArrayDeque<>();

       // Add elements to stack
       stack.push("Ele1");
       stack.push("Ele2");
       stack.push("Ele3");
       System.out.println("Stack: " + stack);

       // Access element from top of stack
       String element = stack.peek();
       System.out.println("Accessed Element: " + element);

       // Remove elements from top of stack
       String remElement = stack.pop();
       System.out.println("Removed element: " + remElement);
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Stack: [Ele3, Ele2, Ele1]
Accessed Element: Ele3
Removed element: Ele3

Advantages of Using ArrayDeque

  • Faster Performance for Adding/Removing Elements: ArrayDeque provides faster add and remove operations for both ends (front and rear), as it does not require resizing as frequently as an array-based list.
  • No Capacity Limit: ArrayDeque dynamically grows in size as needed, unlike ArrayList or arrays, which are limited by their initial capacity. This ensures it can handle a large number of elements efficiently.
  • Improved Memory Efficiency: Unlike LinkedList, which uses more memory due to the storage of pointers in each node, ArrayDeque uses contiguous memory, resulting in less memory overhead.
  • Supports Both Stack and Queue Operations: ArrayDeque can be used as a stack (LIFO) or a queue (FIFO), making it versatile for various use cases, such as in breadth-first or depth-first search algorithms.
  • Thread-Safety (with External Synchronization): Although ArrayDeque is not thread-safe, its operations are generally faster than other thread-safe collections like ConcurrentLinkedQueue, especially when external synchronization is used.

Disadvantages of Using ArrayDeque

  • Not Thread-Safe: ArrayDeque is not inherently thread-safe, meaning external synchronization is required when used in multi-threaded environments, adding complexity and overhead.
  • No Support for Null Elements: Unlike some other collections like ArrayList, ArrayDeque does not allow storing null elements, which can be limiting in certain scenarios.
  • Memory Wastage in Certain Scenarios: When an ArrayDeque is dynamically resized, it might allocate more memory than needed, potentially wasting memory when the number of elements decreases significantly after growth.
  • Resizing Overhead: While ArrayDeque grows dynamically, resizing can incur overhead, especially when a large number of elements are added in rapid succession.
  • Not Ideal for Random Access: ArrayDeque does not support efficient random access to elements like an ArrayList or Vector because it is designed to be efficient for queue-like or stack-like operations.

Frequently Asked Questions

What is the difference between Deque and ArrayDeque?

At both ends, the Deque interface provides element insertion, removal, and retrieval. The ArrayDeque class implements the Deque interface as a resizeable array, whereas the LinkedList class implements it as a list.

Can we add null in ArrayDeque?

Null cannot be used in an ArrayDeque because functions such as poll() use null as a special return value to signal that the collection is empty. Because null has that meaning, Java bans you from placing one in there.

Does ArrayDeque implement list?

ArrayDeque does not implement List.

Is ArrayDeque better than stack?

ArrayDeque and Stack serve different purposes. While Stack is a legacy class focused on LIFO (Last In, First Out) operations, ArrayDeque offers more functionality like resizable capacity, making it more versatile and efficient for general deque operations.

What is the difference between ArrayDeque and ArrayList?

ArrayDeque is a resizable array implementation of a deque, optimized for adding and removing elements from both ends, whereas ArrayList is a dynamic array designed for random access to elements and adding/removing elements at the end, with slower operations for the beginning.

Conclusion

ArrayDeque in Java is a highly efficient data structure for handling scenarios that require fast insertion and removal of elements from both ends of the queue. Its dynamic resizing, improved memory efficiency, and versatile functionality for stack and queue operations make it a strong choice for many applications.

Recommended problems -

We hope that this blog has helped you enhance your knowledge of the ArrayDeque class in java and if you would like to learn more about java, check out our articles, java archives

Live masterclass