Queue in Java
Queue is a collection interface for elements waiting to be processed. The head is the element that will be removed next. Many queues use first-in, first-out order, but the ordering rule depends on the implementation.
Why Do We Need This?
A help desk can process requests in arrival order. Other tasks may need a priority rule so the most urgent item is selected first. Both can use queues, but they need different implementations.
Main Ideas
| Concept | What it means |
|---|---|
| offer(value) | Attempts to add an element |
| peek() | Reads the head, or returns null when empty |
| poll() | Removes the head, or returns null when empty |
| PriorityQueue | Selects the head by priority rather than arrival order |
| Deque | Allows operations at both ends |
Simple Working Example
Run this program on its own. All required imports and classes are included.
import java.util.ArrayDeque;
import java.util.Queue;
public class HelloWorld {
public static void main(String[] args) {
Queue<String> requests = new ArrayDeque<>();
requests.offer("Print notes");
requests.offer("Print exercise");
System.out.println("Next: " + requests.peek());
System.out.println("Processing: " + requests.poll());
System.out.println("Remaining: " + requests.poll());
System.out.println("Empty result: " + requests.poll());
}
}Output
Next: Print notes
Processing: Print notes
Remaining: Print exercise
Empty result: nullArrayDeque behaves as a FIFO queue through these operations. peek leaves the first request in place; poll removes it. This implementation does not allow null elements and is not thread-safe.
Topics in This Section
Easy Way to Remember
Do not assume every queue is FIFO. Check the head-selection rule, empty behavior, capacity, and thread-safety requirements.
See you in next page....??