Java Queue
Java Queue
The Queue interface is part of the Java Collections Framework.
It is used to store elements in a specific order: FIFO (First In, First Out).
FIFO means the first element added is also the first one to be removed. Think of it like a line at the supermarket: the first person in line is the first one to be served.
Notes on Queues
- FIFO order: First element in, first element out
- Allows duplicates
- No index access: You cannot get elements by index like in a List
Since Queue is an interface, you cannot create a Queue directly.
Instead, use one of these classes that implement it:
PriorityQueue- Orders elements based on priorityArrayDeque- Fast and efficient queue that supports both endsLinkedList- Can be used as a queue and also works like a list
Use PriorityQueue when sorting is important,
ArrayDeque for performance, and
LinkedList when you want a queue that can also behave like a list.
Queue vs. List
| Feature | Queue |
List |
|---|---|---|
| Element order | FIFO (first-in, first-out) | Indexed order (position-based) |
| Duplicates | Allowed | Allowed |
| Access type | No direct index access | Access by index (get, set) |
| Use case | Task scheduling, messaging | General data storage and lookup |
Next Steps
Now that you understand what a Queue is, explore how it works with different classes: