![]() |
VOOZH | about |
The Deque interface is part of the java.util package and extends the Queue interface. It stands for Double-Ended Queue and represents a linear collection that allows insertion, removal, and retrieval of elements from both ends.
public interface Deque<E> extends Queue<E>
Here, E is the type of elements stored in the deque.
First: 1, Last: 2
It extends the Queue interface which extends the Collection Interface. It has implementation classes like ArrayDeque and LinkedList.
Letβs see how to perform a few frequently used operations on the Deque using the ArrayDeque class.
To add elements in a Deque, you can use add() , addFirst(), or addLast(), allowing insertion at either end, unlike a standard Queue which only adds at the tail.
[Geeks, For, Geeks]
Elements can be removed from both ends using removeFirst(), removeLast(), pop(), or poll() variants; pop() throws an exception if empty, while poll() is safe.
[Geeks, For, Geeks] Geeks For Geeks null
Since a Deque can be iterated from both directions, the iterator method of the Deque interface provides us two ways to iterate. One from the first and the other from the back.
Geeks For Geeks is so good is so good Geeks For Geeks
Below are some common list of methods of Deque Interface
| Method | Description |
|---|---|
| addFirst(E e) | Inserts element at the front (head). |
| addLast(E e) | Inserts element at the end (tail). |
| offerFirst(E e) | Adds element at head; returns false if unable. |
| offerLast(E e) | Adds element at tail; returns false if unable. |
| add(E e) | Adds element at the tail. |
Adds element at the tail. | |
| removeFirst() | Removes and returns first element; throws exception if empty. |
| removeLast() | Removes and returns last element; throws exception if empty. |
| pollFirst() | Removes and returns first element; returns null if empty. |
| pollLast() | Removes and returns last element; returns null if empty. |
| poll() | Removes and returns head safely; returns null if empty. |
| getFirst() | Retrieves first element without removing; throws exception if empty. |
| getLast() | Retrieves last element without removing; throws exception if empty. |
| peekFirst() | Retrieves first element safely; returns null if empty. |
| peekLast() | Retrieves last element safely; returns null if empty. |
| peek() | Retrieves head element safely; returns null if empty. |
| push(E e) | Inserts element at the head (top of stack). |