A Queue in Java is a collection used to hold elements prior to processing. It follows FIFO (First-In-First-Out) order by default, while some implementations like PriorityQueue allow custom ordering.
Part of the java.util package.
Extends Collection interface.
Common operations:
| Method | Description |
|---|---|
add(e) | Inserts an element (throws exception if full) |
offer(e) | Inserts an element (returns false if full) |
remove() | Removes and returns head (throws exception if empty) |
poll() | Removes and returns head (returns null if empty) |
element() | Returns head without removing (throws exception if empty) |
peek() | Returns head without removing (returns null if empty) |
Output:
PriorityQueue is a queue that orders elements according to their natural order or a custom comparator.
Does not allow null elements.
Head element is always the smallest/largest depending on ordering.
Implements Queue interface.
Allows efficient access to the element with highest priority.
Internally implemented as a min-heap.
Output:
| Feature | Queue (LinkedList) | PriorityQueue |
|---|---|---|
| Order | FIFO (insertion order) | Natural order or custom comparator |
| Null elements | Allowed | Not allowed |
| Head element | First inserted element | Element with highest priority |
| Implementation | LinkedList | Min-heap |
| Use Case | Task scheduling, BFS | Priority-based scheduling |
Queue → General FIFO behavior.
PriorityQueue → Custom ordering based on priority.
Both implement Queue interface.
Use offer/poll/peek methods for safe operations.
PriorityQueue is not thread-safe; use PriorityBlockingQueue for concurrent scenarios.
Java Queues provide efficient data handling in FIFO order, while PriorityQueue enables priority-based processing. Choosing the right implementation ensures optimal performance and correct task ordering in Java applications.
Take quizzes related to this topic and see where you stand!
Start Quiz Now