new LinkedList<>() / queue.offer() / poll() / peek()
| Since: | Java 5(2004) |
|---|
A queue is a First In First Out (FIFO) data structure. In Java, LinkedList implements the Queue interface and can be used as a queue. Use offer() to add elements, poll() to retrieve and remove them, and peek() to inspect the front element without removing it.
Syntax
// Create a LinkedList as a queue. Queue<Type> queueName = new LinkedList<>(); // Add an element to the tail. queue.offer(element); // Retrieve and remove the head element (returns null if empty). queue.poll(); // Inspect the head element without removing it (returns null if empty). queue.peek(); // Check whether the queue is empty. queue.isEmpty();
Method List
| Method | Description |
|---|---|
| new LinkedList<>() | Creates a queue (or deque) backed by a doubly linked list. |
| offer(E e) | Adds an element to the tail. Returns true if the element was added successfully. |
| poll() | Retrieves and removes the head element. Returns null if the queue is empty. |
| peek() | Returns the head element without removing it. Returns null if the queue is empty. |
| isEmpty() | Returns a boolean indicating whether the queue is empty. |
Sample Code
sample_QueueOfferPoll.java
import java.util.LinkedList;
import java.util.Queue;
class QueueOfferPoll {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// Add elements to the tail.
queue.offer("Kogami Shinya");
queue.offer("Tsunemori Akane");
queue.offer("Ginoza Nobuchika");
// Inspect the head element without removing it.
System.out.println(queue.peek()); // Prints "Kogami Shinya".
// Retrieve and remove the head element.
System.out.println(queue.poll()); // Prints "Kogami Shinya".
System.out.println(queue.poll()); // Prints "Tsunemori Akane".
// Check the size.
System.out.println(queue.size()); // Prints "1".
// Retrieve all elements in order.
Queue<Integer> numQueue = new LinkedList<>();
numQueue.offer(10);
numQueue.offer(20);
numQueue.offer(30);
while (!numQueue.isEmpty()) {
System.out.println(numQueue.poll()); // Prints 10, 20, 30 in order.
}
}
}
QueueOfferPoll.java
javac QueueOfferPoll.java java QueueOfferPoll Kogami Shinya Kogami Shinya Tsunemori Akane 1 10 20 30
Notes
Both offer() and add() add an element to the queue, but when a capacity-restricted queue cannot accept the element, offer() returns false while add() throws an exception. It is generally recommended to use the safer offer().
Similarly, both poll() and remove() retrieve the head element, but when called on an empty queue, remove() throws an exception whereas poll() returns null. Check with isEmpty() before retrieving, or use poll().
For stack and deque operations, see 'new ArrayDeque<>() / push() / pop()'.
If you find any errors or copyright issues, please contact us.