The Queue interface is part of the Java Collections Framework and is used to hold multiple elements prior to processing. Queues typically, but not necessarily, order elements in a FIFO (First-In-First-Out) manner.
Common Implementations:
LinkedList
: Implements the Queue interface and provides methods for queue operations.PriorityQueue
: An unbounded priority queue based on a priority heap.Key Methods:
add(E e)
: Inserts the specified element into the queue. Throws an exception if the operation fails.offer(E e)
: Inserts the specified element into the queue. Returns false if the operation fails.remove()
: Retrieves and removes the head of the queue. Throws an exception if the queue is empty.poll()
: Retrieves and removes the head of the queue. Returns null if the queue is empty.element()
: Retrieves, but does not remove, the head of the queue. Throws an exception if the queue is empty.peek()
: Retrieves, but does not remove, the head of the queue. Returns null if the queue is empty.Example Using Queue Interface:
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
// Add elements to the queue
queue.add(1);
queue.add(2);
queue.add(3);
// Display elements
System.out.println("Queue: " + queue);
// Remove an element
int removed = queue.remove();
System.out.println("Removed element: " + removed);
// Display the head element
int head = queue.peek();
System.out.println("Head of the queue: " + head);
// Display elements after removal
System.out.println("Queue after removal: " + queue);
}
}