1. The Queue interface: the classic queue (FIFO)
In programming, as in life, there are situations where it’s important not just to store a set of elements, but to control the order in which they are processed. Think of a supermarket line: those closer to the front are served earlier. That’s the FIFO principle — “first in, first out”. A stack of plates in a cupboard follows LIFO — “last in, first out”. In Java, these principles are embodied by collections: queues Queue, double-ended queues Deque, and stacks Stack.
Where it is used:
- Processing tasks in the order they arrive (task queue, printing documents, event handling).
- Undo/redo — a stack.
- Parsing expressions, traversing trees and graphs (breadth/depth search), and much more.
What is a queue?
A queue (Queue) is a collection based on FIFO. Elements are added to the end and removed from the front. Like at a store: whoever arrives earlier is served first.
Key methods of the Queue interface
| Method | What it does | Returns |
|---|---|---|
|
Adds an element to the end (no exception) | true/false |
|
Adds an element to the end (throws an exception) | true/Exception |
|
Removes and returns the first element | element/null |
|
Removes and returns the first element | element/Exception |
|
Returns the first element without removing it | element/null |
|
Returns the first element without removing it | element/Exception |
You’ve probably noticed pairs of methods with similar behaviour. The difference is the “softness”: offer, poll, peek return a special value on failure (typically null or false) and do not throw exceptions, whereas add, remove, element throw exceptions in edge situations (empty queue, sometimes capacity issues).
Example: task queue
import java.util.*;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> tasks = new LinkedList<>();
tasks.offer("Brush teeth");
tasks.offer("Do a workout");
tasks.offer("Have coffee");
while (!tasks.isEmpty()) {
String task = tasks.poll(); // Take a task from the head of the queue
System.out.println("Doing: " + task);
}
}
}
Output:
Doing: Brush teeth
Doing: Do a workout
Doing: Have coffee
Why is LinkedList used so often?
An interface is a contract, and there are several implementations. LinkedList is often used because it can quickly add/remove at both ends. However, an excellent alternative is ArrayDeque. There are also specialised options: PriorityQueue (a priority queue), covered below.
2. The Deque interface: a double-ended queue
Deque (double-ended queue, “deck”) is a queue where you can add and remove elements from both sides: from the front and from the back. Like a bus with two doors: you can get in/out from either side.
Deque = a universal tool: it can work as a regular queue (FIFO), as a stack (LIFO), or as a hybrid.
Key methods of the Deque interface
| Method | What it does | Example usage |
|---|---|---|
|
Add to the front | |
|
Add to the back | |
|
Remove and return from the front | |
|
Remove and return from the back | |
|
Peek front (without removing) | |
|
Peek back (without removing) | |
|
Add to the front (no exception) | |
|
Add to the back (no exception) | |
Example: Deque as a queue and as a stack
import java.util.*;
public class DequeDemo {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
// Use it as a queue (FIFO)
deque.offerLast("A");
deque.offerLast("B");
deque.offerLast("C");
System.out.println("Queue (FIFO):");
while (!deque.isEmpty()) {
System.out.println(deque.pollFirst());
}
// Use it as a stack (LIFO)
deque.offerLast("1");
deque.offerLast("2");
deque.offerLast("3");
System.out.println("Stack (LIFO):");
while (!deque.isEmpty()) {
System.out.println(deque.pollLast());
}
}
}
Output:
Queue (FIFO):
A
B
C
Stack (LIFO):
3
2
1
Why ArrayDeque?
ArrayDeque is a fast, compact array-based implementation of Deque. For stacks and queues it’s usually faster and more reliable than the old Stack, and it has no fixed capacity (limited only by memory).
3. Stack: last in, first out (LIFO)
A stack follows the LIFO principle: you pop the element that was pushed last. In programming, a stack is useful for action history (undo), traversing recursive structures (trees/graphs), evaluating expressions, etc.
The Stack class (and why you shouldn’t use it)
Java has a Stack class that extends the legacy Vector. It’s not recommended for new projects. Prefer Deque/ArrayDeque.
Stack methods (Deque)
| Method | What it does |
|---|---|
|
Push an element onto the top of the stack |
|
Pop and return the top element |
|
Peek the top element |
Note: in Deque these operations correspond to addFirst/removeFirst/peekFirst, but for compatibility there are also the “stack” names push/pop/peek.
Example: a stack on ArrayDeque
import java.util.*;
public class StackDemo {
public static void main(String[] args) {
Deque<String> stack = new ArrayDeque<>();
stack.push("First");
stack.push("Second");
stack.push("Third");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
Output:
Third
Second
First
Why not Stack?
- Stack is synchronised (slower) and extends the legacy Vector.
- ArrayDeque is usually faster and more compact, and it doesn’t block threads.
- If you see Stack in new code, it’s usually a candidate to replace with ArrayDeque.
4. When to use what
| Structure | Principle | Use cases | Example implementation |
|---|---|---|---|
| Queue | FIFO | Task queues, event handling, printing, customer queues | |
| Stack | LIFO | Undo/redo, recursion, parsers, tree traversal | |
| Deque | FIFO/LIFO | Buffers, palindromes, double-ended queues, general-purpose tasks | |
Real-world analogies:
- A bank line — Queue.
- Editor action history — Stack.
- A bus queue with entry/exit on both ends — Deque.
5. Code examples: implement a queue and a stack in a mini app
Example 1: Document print queue
import java.util.*;
public class PrintQueueApp {
public static void main(String[] args) {
Queue<String> printQueue = new ArrayDeque<>();
printQueue.offer("Document1.pdf");
printQueue.offer("Document2.docx");
printQueue.offer("Document3.xls");
while (!printQueue.isEmpty()) {
String doc = printQueue.poll();
System.out.println("Printing: " + doc);
}
}
}
Example 2: Undo stack
import java.util.*;
public class UndoStackApp {
public static void main(String[] args) {
Deque<String> undoStack = new ArrayDeque<>();
undoStack.push("Insert text");
undoStack.push("Change color");
undoStack.push("Delete image");
System.out.println("Last action: " + undoStack.peek()); // Delete image
while (!undoStack.isEmpty()) {
System.out.println("Undo: " + undoStack.pop());
}
}
}
Example 3: Double-ended queue
import java.util.*;
public class DequeApp {
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("A");
deque.addLast("B");
deque.addFirst("C");
deque.addLast("D");
System.out.println("Removing from the front: " + deque.removeFirst()); // C
System.out.println("Removing from the back: " + deque.removeLast()); // D
System.out.println("Remaining: " + deque); // [A, B]
}
}
6. Implementation details and nuances
- ArrayDeque is the fastest and most versatile queue/stack implementation for most tasks.
- LinkedList also implements Deque; it can be useful, but for short queues it’s usually slower than ArrayDeque.
- PriorityQueue is a priority queue: order is defined by priority (natural or via a Comparator); it is not a regular FIFO queue.
- Stack is legacy and synchronised; in new projects prefer ArrayDeque.
- Deque is convenient because it lets you work with both the head and the tail, covering queue and stack scenarios with a single abstraction.
7. Common mistakes when working with queues and stacks
Mistake #1: Using Stack instead of Deque.
Many beginners see the Stack class and choose it “by name”. In modern projects, use ArrayDeque (or LinkedList) with push/pop methods instead.
Mistake #2: Violating the data structure’s principle.
Trying to access queue/stack elements by index, for example queue.get(0) or stack.get(0). Don’t do that — use the appropriate queue/stack methods (peek, poll, pop, etc.).
Mistake #3: Using remove()/element()/add() without checks.
The methods remove, element, add can throw an exception when the structure is empty/full. It’s safer to use the “soft” offer, poll, peek, which return special values.
Mistake #4: Using ArrayDeque with null elements.
ArrayDeque does not permit null. Trying to add null will result in a NullPointerException.
Mistake #5: Using PriorityQueue as a regular queue.
In PriorityQueue, order is defined by priorities (natural or provided via a Comparator). For strict FIFO, use ArrayDeque or LinkedList.
Mistake #6: Modifying a queue/stack during a for-each loop.
Removing elements from a collection during a for-each can lead to a ConcurrentModificationException. For removal, use an iterator or the poll/pop methods in a loop, as shown in the examples.
GO TO FULL VERSION