Java Queue
Interface
Master FIFO patterns using the Queue interface: offer, poll, and peek for clean, predictable data processing.
What Is a Queue?
A Queue is a data structure that follows the First-In, First-Out (FIFO) principle. The element added first is the element removed first: like a line of people at a ticket counter.
The Queue Interface in Java
In Java, Queue is an interface in the java.util package. It extends Collection and defines the contract for FIFO behavior. You cannot instantiate it directly: you must use an implementing class.
Why Use a Queue?
Core Methods: offer, poll, peek
Throwing vs. Non-Throwing Methods
| Operation | Throws Exception | Returns null/false |
|---|---|---|
| Insert | add(e) | offer(e) |
| Remove | remove() | poll() |
| Examine | element() | peek() |
Queue vs. Stack vs. List
| Feature | Queue | Stack | List |
|---|---|---|---|
| Order | FIFO | LIFO | Indexed |
| Insert | offer (rear) | push (top) | add (any index) |
| Remove | poll (front) | pop (top) | remove (any index) |
| Inspect | peek (front) | peek (top) | get (any index) |
| Random Access | No | No | Yes |
How to Apply the Queue Pattern
Example 1: Basic Operations
Example 2: Processing Loop
A common pattern is to drain a queue with a while loop, processing each element in FIFO order:
Example 3: BFS with a Queue
Breadth-First Search (BFS) is the classic queue application. The queue ensures nodes are visited level by level.
Visualizing BFS Order
ArrayDeque vs. LinkedList
| Feature | ArrayDeque | LinkedList |
|---|---|---|
| Underlying structure | Resizable array | Doubly linked list |
| Null elements | Not allowed | Allowed |
| Memory overhead | Lower (contiguous) | Higher (node objects) |
| Performance | Faster (cache friendly) | Slower (pointer chasing) |
| Thread-safe | No | No |
Queue Inside the Deque Hierarchy
Common Mistakes
Queue Cheat Sheet
| Method | Action | On Empty / Full | Time |
|---|---|---|---|
| offer(e) | Insert at rear | Returns false | \(O(1)\) |
| poll() | Remove from front | Returns null | \(O(1)\) |
| peek() | View front | Returns null | \(O(1)\) |
| isEmpty() | Check if empty | Returns true | \(O(1)\) |
| size() | Count elements | Returns 0 | \(O(1)\) |
Question 1 of 5
Which method removes and returns the front element of a Queue, returning null if the queue is empty?
Question 2 of 5
What does the following code print?
Question 3 of 5
Which Queue implementation does the Java documentation recommend as the default choice?
Question 4 of 5
Why is PriorityQueue NOT suitable when you need strict FIFO ordering?
Question 5 of 5
What is the correct pattern to safely process all elements in a Queue?