Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is ArrayDeque in Java?
3.
Hierarchy of ArrayDeque Class in Java
4.
Interfaces Implemented by ArrayDeque
5.
ArrayDeque Class Constructors
6.
Methods of ArrayDeque in Java
7.
Examples of ArrayDeque Class?
7.1.
Addition of Elements
7.2.
Java
7.3.
Accessing the Elements
7.4.
Java
7.5.
Removing Elements
7.6.
Java
7.7.
Iterating through the Deque
7.8.
Java
7.9.
ArrayDeque as a Stack
7.10.
Java
8.
Frequently Asked Questions
8.1.
What is the difference between Deque and ArrayDeque?
8.2.
Can we add null in ArrayDeque?
8.3.
Does ArrayDeque implement list?
8.4.
Is ArrayDeque better than stack?
9.
Conclusion
Last Updated: May 13, 2024
Easy

ArrayDeque in Java

Author Sanjana Yadav
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In Java, the ArrayDeque 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 in Java

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

Also read, Duck Number in Java and Hashcode Method in Java

What is ArrayDeque in Java?

ArrayDeque in Java is a resizable, array-based implementation of the Deque interface. It provides a double-ended queue (Deque) that supports operations at both ends efficiently. 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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

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?

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);
}
}

Output

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


Practice by yourself on online java compiler.

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);
   }
}

Output

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

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);
   }
}

Output

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

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(", ");
       }
   }
}


Output

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

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);
   }
}

Output

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

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.

Conclusion

In this article, we have extensively discussed the ArrayDeque class in java. We learned about the constructors and methods of the ArrayDeque class. In the end, we saw several operations that can be performed using various methods of ArraDeque class with the help of examples.

 

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 archivesPriority Queue in Java. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Introduction to Deque its applications
Next article
What is a Multimap in Java?
Live masterclass