A Queue is a data structure that follows the First In, First Out (FIFO) principle. This means that the element that is inserted first will be the first to be removed, just like a queue in real life (e.g., standing in line at a ticket counter).
In Java, the Queue interface is a part of the java.util package and is used to represent a collection of elements that need to be processed in a specific order.
- Enqueue (add): Adds an element to the end of the queue.
- Dequeue (remove): Removes the element from the front of the queue.
- Peek: Retrieves, but does not remove, the element at the front of the queue.
Queue Operations
- offer(E e): Adds an element to the queue (returns
true
if the element is added successfully). - poll(): Removes and returns the front element of the queue (returns
null
if the queue is empty). - peek(): Retrieves the front element without removing it (returns
null
if the queue is empty). - size(): Returns the number of elements in the queue.
- isEmpty(): Checks if the queue is empty.
Common Implementations of Queue
Java provides different ways to implement queues, and some of the most commonly used classes are:
- LinkedList: Implements both the List and Queue interfaces, making it suitable for a queue with dynamic size.
- PriorityQueue: A queue where elements are ordered according to their natural ordering or by a comparator provided at the time of construction.
- ArrayDeque: A resizable array implementation of the Deque interface, which allows elements to be added or removed from both ends of the queue.