LinkedList &
Queue Interface
Master FIFO patterns in Java using the Queue interface and LinkedList implementation: the backbone of orderly data processing.
What Is a Queue?
A queue is a data structure that follows the First-In, First-Out (FIFO) principle: the first element added is the first one removed. Think of a line at a coffee shop: the person who arrives first gets served first.
The Queue Interface in Java
Java provides a Queue interface in the java.util package. It defines the contract for FIFO behavior without dictating how it is implemented.
Why LinkedList for Queues?
A LinkedList is a chain of nodes, where each node holds a value and a reference to the next node. This structure makes adding to the tail and removing from the head both constant-time operations.
Core Queue Methods
Throws vs Returns Null
| Operation | Throws Exception | Returns null / false |
|---|---|---|
| Insert | add(e) | offer(e) |
| Remove | remove() | poll() |
| Examine | element() | peek() |
Queue vs Stack
How to Use a Queue: Step by Step
Example 1: Basic Queue Operations
Example 2: Processing a Task Queue
Example 3: Customer Service Simulation
Generics and Type Safety
The angle brackets <Type> enforce what kind of objects the queue can hold. This catches type errors at compile time instead of at runtime.
Real-World FIFO Patterns
Common Mistakes
Queue Methods: Summary
| Method | Action | Returns | If Empty? |
|---|---|---|---|
| offer(e) | Add to back | true | N/A |
| poll() | Remove front | element | null |
| peek() | View front | element | null |
| isEmpty() | Check size | boolean | true |
| size() | Count items | int | 0 |
Question 1 of 5
What does FIFO stand for?
Question 2 of 5
Consider this code:
Queue<String> q = new LinkedList<>();
q.offer("X");
q.offer("Y");
q.offer("Z");
q.poll();
q.offer("W");
System.out.println(q.peek());
What is printed?
Question 3 of 5
What does poll() return when called on an empty queue?
Question 4 of 5
Which declaration follows the best practice of programming to the interface?
Question 5 of 5
Consider this code:
Queue<Integer> q = new LinkedList<>();
for (int i = 10; i <= 50; i += 10) {
q.offer(i);
}
q.poll();
q.poll();
int sum = 0;
while (!q.isEmpty()) {
sum += q.poll();
}
What is the value of sum after execution?