Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. new LinkedList<>() / queue.offer() / poll() / peek()

new LinkedList<>() / queue.offer() / poll() / peek()

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

MethodDescription
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

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

Queue<String> queue = new LinkedList<>();

// Add elements to the tail.
queue.offer("first");
queue.offer("second");
queue.offer("third");

// Inspect the head element without removing it.
System.out.println(queue.peek()); // Prints "first".

// Retrieve and remove the head element.
System.out.println(queue.poll()); // Prints "first".
System.out.println(queue.poll()); // Prints "second".

// 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.
}

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 .