×

ArrayDeque in Java

ArrayDeque

The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This extraordinary exhibit develops and permits clients to add or eliminate a component from the two sides of the line. It is also known as Array double-ended queue or Array Deck.

Essential features of ArrayDeque

  • ArrayDeques have no scope of limitation and develop as requisite to support usage.
  • ArrayDeques are not safe as the thread, which intends that without outside synchronization, ArrayDeque doesn't uphold simultaneous access by various threads.
  • Invalid components are disallowed in the ArrayDeque.
  • ArrayDeque class will probably be quicker than Stack when utilized as a stack.
  • ArrayDeque class will probably be faster than LinkedList when used as a Queue.

Interfaces Carried out by ArrayDeque:

There are mainly two interfaces involved in implementing ArrayDeque class

  • Queue Interface: An Interface that follows the First In First Out Data structure and adds elements from the rear end.
  • Deque Interface: An interface that implements a queue with two lots to add an element.

ArrayDeque carries out by both Queue and Deque. It is progressively resizable from both ends. All carried out the interface of ArrayDeque in the order are Serializable, Cloneable, Iterable<E>, Collection <E>, Deque<E>, Queue<E>

Note:

Deque interface extends from Queue interface, and Queue interface extends Collection interface, but ArrayDeque implements from Queue interface and Deque Interface.

Syntax: 

public class ArrayDeque<Element> 

Extends 

AbstractCollection<Elements>

 Implements

 Deque<Element>, Cloneable, Serializable

Now, we will discuss the constructors been used to implement Arraydeque to perceive the better output.

Constructors

  • ArrayDeque(): This constructor is utilized to make a vacant ArrayDeque and naturally holds an underlying ability to have 16 elements.

Syntax:

ArrayDeque<Element> ad = new ArrayDeque<Element>();
  • ArrayDeque(Collection<?extends Elements> c): This constructor is utilized to make an ArrayDeque containing every one of the elements equivalent to that of the predefined Collection.

Syntax:

ArrayDeque<Element> ad = new ArrayDeque<Element>(Collection col);
  • ArrayDeque(int numberofElements): This constructor is utilized to make a vacant ArrayDeque and holds the ability to contain a predetermined number of elements.

Syntax:

ArrayDeque<E> Ad = new ArrayDeque<Element>(int numberofElements);

Program

// program to Implement ArrayDeque in Java
// Importing util package 
import java.util.*;
class Jtp 
 {
    public static void main(String s[])
    {
        // Creating deque And Initialising with an integer
        Deque<Integer> dq = new ArrayDeque<Integer>(1);//Declaring object 
   //Operation 1 – add method
        // Adding elements using add() method in ArrayDeque
        System.out.println("Add the elements ");
        dq.add(1);
        dq.add(2);
        dq.add(3);
        dq.add(4);
        dq.add(5);
        dq.add(6);


        // printing all elements using for each loop
        for (Integer ele : dq)
         {
          System.out.println("Element is  : " + ele);
        }
        // Operation 2 – clear Method
        System.out.println("Clearing all elements");
           dq.clear();
 
        // Operations 3 -  addFirst() method
      System.out.println(“adding elements at First " );
 
        dq.addFirst(965);
        dq.addFirst(233);
        dq.addFirst(356);
 
        // Operation 4-  addLast() method
        // Inserting at last
         System.out.println("adding elements at Last");
        dq.addLast(113);
        dq.addLast(146);
         dq.addLast(246);
        // Display message
        System.out.println("Iterator- Elements of deque:");
 
        for (Iterator it = dq.iterator();it.hasNext();)
         {
            System.out.println(it.next());
          }
 
       
        // reverse order using descending Iterator
        System.out.println( "Displaying elements in Reverse order :");
 
        for (Iterator dIt = dq.descendingIterator();dIt.hasNext();) 
             {
            System.out.println(dIt.next());
        }
 


   // Operation 5- element() method 
        System.out.println( "\nHead Element using element method is "+ dq.element());
// Operation 6 - getFirst() method :
        System.out.println("Head Element using getFirst(): " + dq.getFirst());


// Operation 7- getLast() method 
        System.out.println("Last Element using getLast(): "
                           + dq.getLast());
// Operation 8 - toArray() method 
        Object[] a = dq.toArray();
        System.out.println("\nArray Size : " + a.length);
 
        System.out.print("Array elements are : ");
 
        for (int i = 0; i < a.length; i++)
          {
            System.out.print(" " + a[i]);
            }
 
        // Operation 9 - peek() method 
        System.out.println("\nHead element using Peek is : " + dq.peek());
 
        // Operation 10 - poll() method 
        System.out.println("Head element using poll is : "+ dq.poll());
 
        // Operation 11- push() method
        dq.push(287);
        dq.push(786);
        dq.push(123);
 
        // Operation 12- remove() method
 System.out.println("After removing Head Element: " + dq.remove());
 
        System.out.println("The final array is: " + dq);
 
  }
}

Output:

Add the elements
Element is  : 1
Element is  : 2
Element is  : 3
Element is  : 4
Element is  : 5
Element is  : 6
Clearing all elements
adding elements at First
adding elements at Last
Iterator- Elements of deque:
356
233
965
113
146
246
Displaying elements in Reverse order :
246
146
113
965
233
356


Head Element using element method is 356
Head Element using getFirst(): 356
Last Element using getLast(): 246


Array Size : 6
Array elements are :  356 233 965 113 146 246
Head element using Peek is : 356
Head element using poll is : 356
After removing Head Element: 123
The final array is: [786, 287, 233, 965, 113, 146, 246]

In this session, we will discuss the methods and operations of Array Deque in Java.

Specific methods and operations are involved in array deque to manipulate the data.

Methods and Operations

If there is some slack in clarity in this model, provided that it is accurate and we are proposing different procedures on the ArrayDeque class. Let's perceive how to play out a couple of regularly utilized methods on the ArrayDeque to comprehend better the tasks we have involved above to represent Array Deque in general.

  • Adding or inserting operations
  • Accessing or displaying operations
  • Removing, deleting, or clearing operations
  • Iterating through the Deque

Let’s discuss every operation and method by providing a java program.

Operation 1: Adding or Inserting Elements

There are several methods to implement or add an element in ArrayDeque, we can use the methods  add(), addFirst(), addLast(), offer(), offerFirst(), offerLast() methods.

  1. add() – to add an element at random positions
  2. addFirst() – to add an element at the First of the array deque
  3. addLast() – to add an element at the last of the array deque
  4. offer() – to insert an element at regular positions
  5. offerFirst() – to insert an element at first of the array deque
  6. offerLast()- to insert an element at the last of the array deque

Program

// program to Add elements using different methods in array deque


// Importing packages
import java.io.*;
import java.util.*;
// AddingElementsToArrayDeque
public class Jtp {
 
    // Main method
    public static void main(String s[])
    {
// initialize a deque and consider a string as the collection
        Deque<String> ad= new ArrayDeque<String>();
 
        // add() method 
        ad.add("The");
        ad.addFirst("To");
        ad.addLast("Tutorialandexample");
 
        // offer() method to insert
        ad.offer("Tutorial");
        ad.offerFirst("Welcome");
        ad.offerLast("Kudos");
 
        // Printing Elements of ArrayDeque to the console
        System.out.println("ArrayDeque : " + ad);
    }
}

Output:

ArrayDeque : [Welcome, To, The, Tutorialandexample, Tutorial, Kudos]

Operation 2: Accessing the Elements

Next we can certain operation to access the added elements using getFirst(), getLast(),peek(),peekFirst(),peekLast() methods.

  1. getFirst()      -  to access the first element of the array deque
  2. getLast()       -  to access the last element of array deque
  3. peek()           – to access the peek element of the deque
  4. peekFirst()     - to access the First element of the peek in the deque
  5. peekLast()      - to access the First element of the peek in a deque

Program

// program to Access the inserted Elements of ArrayDeque
// Importing packages
import java.io. *;
import java.util.*;
 class Jtp {
 
    // Main method
    public static void main(String s[])
    {
        // Creating an empty ArrayDeque
        ArrayDeque<String> ad = new ArrayDeque<String>();
 
        // firstly, insert the custom  elements 
        ad.add("Welcome");
        ad.add("To");
        ad.add("Tutorialandexample");
        ad.add("Tutorial");
        ad.add("Kudos");
 
        // Displaying the ArrayDeque
        System.out.println("ArrayDeque: " + ad);
 
   // accessing and displaying the First element of ArrayDeque using the getFirst() method
        System.out.println("The first element is: "   + ad.getFirst());
 
   // accessing and displaying the First element of ArrayDeque using the getlast() method
        System.out.println("The last element is: "+ ad.getLast());


// accessing and displaying the peak element of ArrayDeque using the peek() method
        System.out.println("The peek element is: "   + ad.peek());


// displaying the First peek of ArrayDeque using the peekFirst() method
        System.out.println("The first peek element is: "   + ad.peekFirst());


// displaying the last peek element of ArrayDeque using the peekLast() method
        System.out.println("The Last peek element is: "   + ad.peekLast());


    }
}

Output:

ArrayDeque: [Welcome, To, Tutorialandexample, Tutorial, Kudos]
The first element is: Welcome
The last element is: Kudos
The peek element is: Welcome
The first peek element is: Welcome
The Last peek element is: Kudos

Operation 3. Removing or Deleting Elements

There are various methods available to remove or delete an element from an array deque. In Array deque, we can remove the elements from both ends. To implement the delete we can use remove (), poll() and pop() etc. methods.

  • remove() – it removes an element from random positions
  • removeFirst() – used to remove an element from the first
  • removeLast() – used to remove an element from the last
  • poll()- used to delete the element from random positions
  • pollFirst() – used to delete the elements from first
  • pollLast() – used to delete the elements from last
  • pop() – it is used to pop the element the deque

Program

// program to implement Removal operations using various methods 
// Importing packages
import java.io.*;
import java.util.*;
 class Jtp {
 
    // Main method
    public static void main(String s[])
    {
        // Initializing deque
        Deque<String> ad = new ArrayDeque<String>();
 
        // initially adding elements to perform removal operations
        ad.add("Welcome");
        ad.add("To");
        ad.add("Tutorialandexample");
       ad.add("tutorial");
       ad.add("Kudos");
// Displaying all the elements of ArrayDeque
        System.out.println("ArrayDeque : " + ad);
 
        // removes an element as a stack from the top/front
        System.out.println(ad.pop());
 
        // removes an element
        System.out.println(ad.poll());
 
        // removes an element from the first
        System.out.println(ad.pollFirst());
 
        // removes an element from the last
        System.out.println(ad.pollLast());
    }
}

Output

ArrayDeque : [Welcome, To, Tutorialandexample, tutorial, Kudos]
Welcome
To
Tutorialandexample
Kudos

Note:

From the above program, we can see that we couldn't execute all the delete operations, and if we do so will get an exception as "no Such Elements Exception."

Operation 4: Iterating through the Deque

Various methods are involved in java to iterate the elements of the array deque. The following methods are mainly used for iteration of elements in array deque.

  • iterator()
  • descendingIterator()

Program

// program for Iteration of Elements in Array Deque
 
// Importing packages
import java.io.*;
import java.util.*;
 class Jtp{
 
    // Main method
    public static void main(String[] args)
    {
        // Declaring and initializing a deque
        Deque<String> ad = new ArrayDeque<String>();
 


        // initially adding elements to perform iteration operations
        ad.add("Welcome");
        ad.add("To");
        ad.add("Tutorialandexample");
       ad.add("tutorial");
       ad.add("Kudos");
       
    // Iterating the elements using Iterator() method  from the front of the queue
        for (Iterator it = ad.iterator(); it.hasNext();) 
{
 
            // Print all the elements
            System.out.print(it.next() + " ");
        }
        System.out.println();
 
        // Iterating the elements in reverse order
        for (Iterator dit = ad.descendingIterator();
             dit.hasNext();)
 {
 
            System.out.print(dit.next() + " ");
        }
    }
}

Output:

Welcome To Tutorialandexample tutorial Kudos
Kudos tutorial Tutorialandexample To Welcome

Related Topics

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.