Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Dequeue Implementaion

Being a Queue subtype all methods in the Queue and Collection interfaces are also available in the Dequeinterface.Since Deque is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Deque implementations in the Java Collections API:

  • • java.util.ArrayDeque
  • • java.util.LinkedList

LinkedList is a pretty standard deque / queue implementation.ArrayDeque stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the ArrayDeque grows as needed, even if it stores its elements in an array.

There are also Queue implementations in the java.util.concurrent package, but I will leave the concurrency utilities out of this tutorial.

Here are a few examples of how to create a Deque instance:

Deque dq = new LinkedList();
Deque dq = new ArrayDeque();


Adding and Accessing Elements :

To add elements to the tail of a Deque, you call its add() method. You can also use the addFirst() andaddLast() methods, which add elements to the head and tail of the deque.

Deque dq = new LinkedList();
dq.add("Tapuuu"); //add element at tail
dq.addFirst("Silan); //add element at head
dq.addLast ("Silan Software); //add element at tail

The order in which the elements added to the Deque are stored internally, depends on the implementation. The two implementations mentioned earlier both store the elements in the order (first or last) in which they are inserted.

You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the element() method. You can also use the getFirst and getLast() methods, which return the first and last element in the Deque. Here is how that looks:

Object firstElement = dq.element();
Object firstElement = dq.getFirst();
Object lastElement =dq.getLast();


Removing Elements :

To remove elements from a deque, you call the remove(), removeFirst() and removeLast methods. Here are a few examples:

Object firstElement = dq.remove();
Object firstElement = dq.removeFirst();
Object lastElement =dq.removeLast();

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext