Queue Methods: offer, poll, and peek
You'll learn how to use LinkedList as a Queue with the three essential, safe operations: offer (add), poll (remove), and peek (inspect).
The Core Idea
While Queue has multiple methods for similar operations, offer(), poll(), and peek() form the "special-value" trio that return indicators instead of throwing exceptions. Think of managing a line at a coffee shop: offer() adds someone to the back of the line, poll() serves and removes the person at the front, and peek() lets you check who's next without serving them yet.
Using LinkedList as a Queue
Queue<String> queue = new LinkedList<>();
// offer: adds element to the tail (back of line)
queue.offer("Alice"); // returns true
queue.offer("Bob"); // returns true
queue.offer("Charlie"); // returns true
// peek: inspects the head without removal
String next = queue.peek(); // "Alice" - front person
System.out.println(next); // Alice
System.out.println(queue.peek()); // Still Alice
// poll: removes and returns element from head
String served = queue.poll(); // "Alice" - removed
System.out.println(served); // Alice
System.out.println(queue.poll()); // Bob - removed
System.out.println(queue.poll()); // Charlie - removed
// Safe behavior on empty queue
System.out.println(queue.poll()); // null (not an exception)
System.out.println(queue.peek()); // null (not an exception)
Why These Methods?
These methods are safe because they don't throw exceptions on failure. poll() and peek() return null when the queue is empty, while offer() returns false if the queue is full (though LinkedList has no capacity limit, so it always returns true).
Key Takeaway: Use offer() to safely add to the tail, poll() to remove from the head, and peek() to inspect the head—all without risking exceptions, making them ideal for FIFO queue operations with LinkedList.