The Queue Interface
The Queue interface extends the Collection interface. It is used to hold elements about to be processed and typically orders elements in a FIFO (First-In-First-Out) manner.
However, Java also provides the Deque (Double Ended Queue) interface, which extends Queue and allows elements to be inserted and removed from both ends.
Queue Operations
Unlike standard collections, Queues have specific methods for insertion, removal, and inspection. These methods exist in two forms: one throws an exception if the operation fails, and the other returns a special value (like null or false).
| Operation | Throws Exception | Returns Special Value |
|---|---|---|
| Insert | add(e) | offer(e) |
| Remove | remove() | poll() |
| Examine | element() | peek() |
1. PriorityQueue
The PriorityQueue class is a popular implementation of the Queue interface. It is not a standard FIFO queue. Instead, elements are ordered based on their natural ordering (like TreeSet), or by a custom Comparator provided at queue construction time.
- The head of this queue is the "least" element with respect to the specified ordering.
- It does not allow
nullelements.
Example
import java.util.PriorityQueue;
import java.util.Queue;
public class LabQueue1 {
public static void main(String args[]) {
// A PriorityQueue of Integers
Queue<Integer> pq = new PriorityQueue<>();
// Adding elements out of order
pq.offer(50);
pq.offer(10);
pq.offer(30);
System.out.println("Head of queue (smallest element): " + pq.peek()); // 10
// Removing elements. They will be removed in sorted order!
System.out.println("Processing: " + pq.poll()); // 10
System.out.println("Processing: " + pq.poll()); // 30
System.out.println("Processing: " + pq.poll()); // 50
}
}
2. ArrayDeque
The ArrayDeque class implements the Deque interface. It uses a resizable array and allows you to operate on both the head and the tail of the queue.
- It is significantly faster than
Stackwhen used as a stack (LIFO). - It is significantly faster than
LinkedListwhen used as a queue (FIFO). - It does not allow
nullelements.
Example (Using ArrayDeque as a FIFO Queue)
import java.util.ArrayDeque;
import java.util.Deque;
public class LabQueue2 {
public static void main(String args[]) {
Deque<String> deque = new ArrayDeque<>();
// Adding to the tail
deque.offer("Customer 1");
deque.offer("Customer 2");
deque.offer("Customer 3");
// Removing from the head (FIFO behavior)
System.out.println("Served: " + deque.poll()); // Customer 1
System.out.println("Next in line: " + deque.peek()); // Customer 2
}
}