Deque in Java with examples

What is java.util.Deque? In this blog, you will learn about Java Deque Interface also its declaration, Constructors, etc. Deque (double-ended queue) is generally pronounced as a deck.


Java Deque Interface

The Deque (double-ended queue) Interface of Java belongs to the Collection framework.

There are methods for inserting and removing elements at both ends of the deque(or deck).

Simultaneously, it implements both stacks and queues. ArrayDeque, LinkedList Classes implements the Deque interface.


Declaration of Deque Interface

public interface Deque<E> extends Queue<E>

Methods of Deque

Deque in Java with examples


ArrayDeque Class

This class provides ease of using a deque(or deck) and resizable array also it has no capacity restrictions. Null elements are not allowed. When used as a stack and LinkedList ArrayDeque is faster.

Constructors

ArrayDeque()

ArrayDeque(Collection<? extends E> c)

ArrayDeque(int numElements)

ArrayDeque class declaration

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

Java ArrayDeque with its methods example

public class ExampleArrayDeque {

    public static void main(String[] args) {
        //Creating Deque 
        Deque<String> deque = new ArrayDeque<String>();
        System.out.println("--- Simple ArrayDeque ---");

        //Adding elements
        deque.add("Naman");
        deque.add("Khushi");
        deque.add("Kartik");

        //Printing elements of deque
        for (String str : deque) {
            System.out.println(str);
        }

        System.out.println("\n" + "--- After the offerFirst(Anand) ---");
        deque.offerFirst("Anand");
        for (String str : deque) {
            System.out.println(str);
        }

        System.out.println("\n" + "--- After the offerLast(Ayush) ---");
        deque.offerLast("Ayush");
        for (String str : deque) {
            System.out.println(str);
        }

        System.out.println("\n" + "--- After the pollFirst() ---");
        deque.pollFirst();
        for (String str : deque) {
            System.out.println(str);
        }

        System.out.println("\n" + "--- After the pollLast() ---");
        deque.pollLast();
        for (String str : deque) {
            System.out.println(str);
        }

        System.out.println("\n" + "peekFirst() " + deque.peekFirst());
        System.out.println("peekLast() " + deque.peekLast());

    }
}
Output
--- Simple ArrayDeque ---
Naman
Khushi
Kartik

--- After the offerFirst(Anand) ---
Anand
Naman
Khushi
Kartik

--- After the offerLast(Ayush) ---
Anand
Naman
Khushi
Kartik
Ayush

--- After the pollFirst() ---
Naman
Khushi
Kartik
Ayush

--- After the pollLast() ---
Naman
Khushi
Kartik

peekFirst() Naman
peekLast() Kartik

That’s enough for a quick overview of java.util.Deque.
Thank you

Leave a Reply

Your email address will not be published.