×

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

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes 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 Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.