Queue and Deque in Java
Introduction
In Java, the Queue and Deque interfaces are part of the java.util package. These interfaces provide ways to manage collections in a first-in-first-out (FIFO) or double-ended manner.
Queue: A collection designed for holding elements prior to processing. It follows FIFO order.
Deque: A double-ended queue that allows elements to be added or removed from both ends.
1. Queue
A Queue in Java is typically implemented using classes like LinkedList or PriorityQueue. Below is an example using LinkedList.
Example: Using Queue
import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { // Create a Queue Queuequeue = new LinkedList<>(); // Add elements to the Queue queue.add("A"); queue.add("B"); queue.add("C"); // Display the Queue System.out.println("Queue: " + queue); // Peek at the head of the Queue System.out.println("Head of Queue: " + queue.peek()); // Remove an element from the Queue System.out.println("Removed: " + queue.poll()); // Display the Queue after removal System.out.println("Queue after removal: " + queue); } }
2. Deque
A Deque (double-ended queue) can be implemented using classes like LinkedList or ArrayDeque. Below is an example using ArrayDeque.
Example: Using Deque
import java.util.ArrayDeque; import java.util.Deque; public class DequeExample { public static void main(String[] args) { // Create a Deque Dequedeque = new ArrayDeque<>(); // Add elements to the front and end deque.addFirst("Front"); deque.addLast("End"); deque.addFirst("New Front"); // Display the Deque System.out.println("Deque: " + deque); // Peek at elements System.out.println("First Element: " + deque.peekFirst()); System.out.println("Last Element: " + deque.peekLast()); // Remove elements from front and end System.out.println("Removed from Front: " + deque.pollFirst()); System.out.println("Removed from End: " + deque.pollLast()); // Display the Deque after removals System.out.println("Deque after removal: " + deque); } }
Differences Between Queue and Deque
Feature | Queue | Deque |
---|---|---|
Operations | Elements are added at the end and removed from the front | Elements can be added or removed from both ends |
Implementation | LinkedList, PriorityQueue | LinkedList, ArrayDeque |
Flexibility | Single-ended | Double-ended |
Conclusion
Both Queue and Deque are useful in different scenarios:
- Queue: Use when you need FIFO operations.
- Deque: Use when you need operations at both ends.