×

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

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

8 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.