Java Deque Handbook

1. Quick Summary

Deque (pronounced "deck") stands for Double Ended Queue. It is a linear collection that supports element insertion and removal at both ends.

  • Interface: java.util.Deque

  • Key Feature: It is the standard, modern replacement for both the legacy Stack class and the basic Queue usage.

  • Implementations:

    • ArrayDeque: Resizable array. Faster for most use cases (stacks, queues). No null allowed.

    • LinkedList: Doubly-linked list. Use only if you need to remove elements from the middle via Iterator.

2. The Three Faces of Deque

A Deque can act as three different data structures depending on which methods you use.

Role

Behavior

Key Methods

Standard Deque

Add/Remove from both ends.

addFirst, addLast, pollFirst, pollLast

Queue (FIFO)

Add to End, Remove from Front.

offerLast (add), pollFirst (remove)

Stack (LIFO)

Add to Front, Remove from Front.

push (addFirst), pop (removeFirst)

3. Essential Methods Cheat Sheet

Operation

Head (First Element)

Tail (Last Element)

Insert (Throw Exception)

addFirst(e)

addLast(e)

Insert (Return Boolean)

offerFirst(e)

offerLast(e)

Remove (Throw Exception)

removeFirst()

removeLast()

Remove (Return Null)

pollFirst()

pollLast()

Examine (Throw Exception)

getFirst()

getLast()

Examine (Return Null)

peekFirst()

peekLast()

4. ArrayDeque vs. LinkedList

Feature

ArrayDeque

LinkedList

Underlying Data

Resizable Array

Doubly Linked Nodes

Memory Efficiency

High (Less overhead)

Low (Node object overhead)

Speed

Faster (Cache locality)

Slower (Pointer chasing)

Null Elements

Forbidden

Allowed

Random Access

No (Traverse only)

No (Traverse only)

5. Implementation Patterns

As a Stack (The Modern Way):

Deque<String> stack = new ArrayDeque<>();
stack.push("Top");stack.pop();

As a Queue:

Deque<String> queue = new ArrayDeque<>();
queue.offer("First");queue.poll();

Iterating:

// Standard iterator (Head to Tail)
for (String s : deque) { ... }
// Reverse iterator (Tail to Head)
Iterator<String> it = deque.descendingIterator();


Examples of implementation



import java.util.Deque;
import java.util.ArrayDeque;
import java.util.LinkedList;
/**
* A comprehensive demonstration of Deque usages.
* Includes:
* 1. Using Deque as a FIFO Queue (Standard Line).
* 2. Using Deque as a LIFO Stack (Modern Stack).
* 3. Using Deque as a Double-Ended structure (Palindrome Checker).
*/
public class DequeExamples {
public static void main(String[] args) {
System.out.println("=== 1. Deque as a Queue (FIFO) ===");
useAsQueue();
System.out.println("\n=== 2. Deque as a Stack (LIFO) ===");
useAsStack();
System.out.println("\n=== 3. Deque as Double-Ended (Palindrome) ===");
String word = "Racecar";
System.out.println("Is '" + word + "' a palindrome? " + isPalindrome(word));
}
/**
* Pattern 1: FIFO (First-In-First-Out)
* Useful for job processing, print queues, or BFS algorithms.
*/
private static void useAsQueue() {
// ArrayDeque is generally faster than LinkedList for Queues
Deque<String> printQueue = new ArrayDeque<>();
// 1. Add to the back (offer/offerLast)
printQueue.offer("Document1.pdf");
printQueue.offer("Image.png");
printQueue.offer("Report.docx");
// 2. Process from the front (poll/pollFirst)
while (!printQueue.isEmpty()) {
System.out.println("Printing: " + printQueue.poll());
}
}
/**
* Pattern 2: LIFO (Last-In-First-Out)
* This is the recommended replacement for the legacy java.util.Stack class.
*/
private static void useAsStack() {
Deque<String> browserHistory = new ArrayDeque<>();
// 1. Push to the "top" (head of the deque)
browserHistory.push("google.com");
browserHistory.push("github.com");
browserHistory.push("stackoverflow.com");
System.out.println("Current Page: " + browserHistory.peek()); // Stack overflow
// 2. Pop from the "top"
while (!browserHistory.isEmpty()) {
System.out.println("Going back from: " + browserHistory.pop());
}
}
/**
* Pattern 3: True Double-Ended Usage
* Example: Checking for Palindromes efficiently.
* We compare the first and last characters, moving inward.
*/
private static boolean isPalindrome(String text) {
Deque<Character> chars = new ArrayDeque<>();
// Fill the deque
for (char c : text.toLowerCase().toCharArray()) {
chars.addLast(c);
}
// Compare ends until 0 or 1 char remains
while (chars.size() > 1) {
char first = chars.removeFirst();
char last = chars.removeLast();
if (first != last) {
return false;
}
}
return true;
}
}
← Back to Learning Journey