Queue

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Queue is an interface designed for holding elements prior to processing.
  • It typically orders elements in a FIFO (First-In-First-Out) manner.
  • Common implementations: LinkedList and PriorityQueue.

Concept

Think of a Queue like a line at a grocery store. The first person in the line is the first person to be served (FIFO).

Method Pairs

The Queue interface provides two sets of methods for common operations. The difference is how they handle failure (like trying to remove from an empty queue, or add to a full bounded queue):

OperationThrows Exception on FailureReturns Special Value (false/null)
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()

Best Practice: Use offer(), poll(), and peek() as they are safer and don’t throw unchecked exceptions when limits are reached.

Examples

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        // LinkedList implements Queue
        Queue<String> line = new LinkedList<>();
        
        // Enqueue (add to the back)
        line.offer("Alice");
        line.offer("Bob");
        line.offer("Charlie");
        
        System.out.println("Line: " + line); // [Alice, Bob, Charlie]
        
        // Peek (look at front without removing)
        System.out.println("Next up: " + line.peek()); // Alice
        
        // Dequeue (remove from the front)
        String served = line.poll();
        System.out.println("Served: " + served); // Alice
        
        System.out.println("Remaining: " + line); // [Bob, Charlie]
    }
}

Interview Questions

Q: What is the difference between poll() and remove()?
A: Both methods remove and return the element at the head of the queue. However, if the queue is empty, remove() throws a NoSuchElementException, whereas poll() simply returns null.

Q: How is a Queue different from a Deque?
A: A Queue is strictly First-In-First-Out (FIFO) and allows insertion only at the tail, and removal only at the head. A Deque (Double Ended Queue) allows insertion and removal at both ends, meaning it can function as a FIFO Queue or a LIFO Stack.