Java Queue & Deque — Explained with Simple Examples
In Java, Queue and Deque are important data structures widely used in real-world systems like messaging, scheduling, caching, undo/redo, browser history, task execution, and more. They come from the java.util package and follow FIFO / LIFO styles of processing.
✅ 1. What is a Queue in Java?
A Queue stores elements in the order they arrive and processes them in the same order.
👉 Works on: FIFO (First In – First Out)
📦 Example in real life: People standing in a line at a ticket counter.
Queue Interface Hierarchy
Common Queue Implementations in Java
| Implementation | Description |
|---|---|
LinkedList | Simple queue (FIFO) |
PriorityQueue | Orders elements by priority (NOT FIFO) |
ArrayDeque | Faster queue without capacity limit |
🔹 Basic Queue Operations
| Method | Description |
|---|---|
| add(e) / offer(e) | Insert element |
| remove() / poll() | Remove head |
| element() / peek() | View head |
💡 Difference between add() & offer()
-
add()→ throws exception if queue is full -
offer()→ returnsfalseif queue is full
🧪 Example 1 — Simple Queue using LinkedList
Output
🧪 Example 2 — PriorityQueue (NOT FIFO)
PriorityQueue orders elements by natural order or custom comparator.
Output
👉 Smallest element gets highest priority.
🧪 Example 3 — Max Priority Queue
Output
✅ 2. What is a Deque in Java?
Deque = Double Ended Queue
You can insert and remove from BOTH ends.
👉 Works as:
-
Queue (FIFO)
-
Stack (LIFO)
Deque Interface Hierarchy
Common Deque Implementation
| Implementation | Description |
|---|---|
ArrayDeque | Most common + fastest |
LinkedList | Also supports Deque |
Deque Operations
Insert
| Method |
|---|
| addFirst() |
| addLast() |
| offerFirst() |
| offerLast() |
Remove
| Method |
|---|
| pollFirst() |
| pollLast() |
| removeFirst() |
| removeLast() |
Peek
| Method |
|---|
| peekFirst() |
| peekLast() |
🧪 Example 4 — Deque as Queue (FIFO)
Output
🧪 Example 5 — Deque as Stack (LIFO)
Output
👉 ArrayDeque is recommended instead of Stack class
because Stack is synchronized & slower.
Queue vs Deque — Quick Comparison
| Feature | Queue | Deque |
|---|---|---|
| Order | FIFO | FIFO + LIFO |
| Insert Ends | Rear only | Both ends |
| Remove Ends | Front only | Both ends |
| Common Impl | LinkedList, PriorityQueue | ArrayDeque |
When to Use What?
| Use Case | Best Choice |
|---|---|
| Simple FIFO tasks | Queue (LinkedList) |
| Priority-based processing | PriorityQueue |
| Stack replacement | Deque |
| Both stack + queue flexibility | ArrayDeque |
Conclusion
Java provides powerful Queue and Deque implementations that are widely used in real-world systems for task scheduling, background processing, messaging, caching, and more.
-
Use Queue when order matters (FIFO)
-
Use PriorityQueue when priority matters
-
Use Deque / ArrayDeque when you need both stack + queue behavior
No comments:
Post a Comment