×

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

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 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.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

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

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

2 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.