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.DequeKey Feature: It is the standard, modern replacement for both the legacy
Stackclass and the basicQueueusage.Implementations:
ArrayDeque: Resizable array. Faster for most use cases (stacks, queues). Nonullallowed.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. |
|
Queue (FIFO) | Add to End, Remove from Front. |
|
Stack (LIFO) | Add to Front, Remove from Front. |
|
3. Essential Methods Cheat Sheet
Operation | Head (First Element) | Tail (Last Element) |
|---|---|---|
Insert (Throw Exception) |
|
|
Insert (Return Boolean) |
|
|
Remove (Throw Exception) |
|
|
Remove (Return Null) |
|
|
Examine (Throw Exception) |
|
|
Examine (Return Null) |
|
|
4. ArrayDeque vs. LinkedList
Feature |
|
|
|---|---|---|
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;
}
}