Deque interface in Java


java.util.Deque interface is a subtype of java.util.Queue interface which supports insertion and removal of elements at both ends.

Interface Declaration

public interface Deque<E>
extends Queue<E>

ArrayDeque Class

The java.util.ArrayDeque class provides resizable-array and implements the Deque interface. Following are the important points about Array Deques −

  • Array deques have no capacity restrictions so they grow as necessary to support usage.

  • They are not thread-safe; in the absence of external synchronization.

  • They do not support concurrent access by multiple threads.

  • Null elements are prohibited in the array deques.

  • They are faster than Stack and LinkedList.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

Class declaration

Following is the declaration for java.util.ArrayDeque class −

public class ArrayDeque<E>
extends AbstractCollection<E>
implements Deque<E>, Cloneable, Serializable

Here <E> represents an Element, which could be any class. For example, if you're building an array list of Integers then you'd initialize it as −

ArrayList<Integer> list = new ArrayList<Integer>();

Class constructors

Sr.No.Constructor & Description
1ArrayDeque()
This constructor is used to create an empty array deque with an initial capacity sufficient to hold 16 elements.
2ArrayDeque(Collection<? extends E> c)
This constructor is used to create a deque containing the elements of the specified collection.
3ArrayDeque(int numElements)
This constructor is used to create an empty array deque with an initial capacity sufficient to hold the specified number of elements.

Example

import java.util.ArrayDeque;
import java.util.Deque;

public class Tester {
   public static void main(String[] args) {

      // create an empty array deque with an initial capacity
      Deque<Integer> deque = new ArrayDeque<Integer>(5);

      // use add() method to add elements in the deque
      deque.add(20);
      deque.add(30);
      deque.add(20);
      deque.add(30);
      deque.add(15);
      deque.add(22);
      deque.add(11);

      // let us print all the elements available in deque
      for (Integer number : deque) {
         System.out.println("Number = " + number);
      }

      // getFirst() will retrieve element at first position
      int first = deque.getFirst();
      System.out.println("Retrieved Element is = " + first);

      // getLast() will retrieve element at last position
      int last = deque.getLast();
      System.out.println("Retrieved Element is = " + last);
   }
}

Output

Number = 20
Number = 30
Number = 20
Number = 30
Number = 15
Number = 22
Number = 11
Retrieved Element is = 20
Retrieved Element is = 11

Updated on: 21-Jun-2020

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements