Working with Java Queues and PriorityQueue
⏱ Estimated reading time: 2 min
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.
1. Queue Interface
-
Part of the
java.utilpackage. -
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) |
Example using LinkedList as Queue
Output:
2. PriorityQueue
-
PriorityQueueis 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.
Features
-
Implements Queue interface.
-
Allows efficient access to the element with highest priority.
-
Internally implemented as a min-heap.
Example:
Output:
3. Key Differences: Queue vs PriorityQueue
| 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 |
4. Key Points
-
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.
5. Conclusion
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.
Register Now
Share this Post
← Back to Tutorials