Java LinkedList poll() Method

Java LinkedList Java LinkedList


poll()The method is in JavaLinkedLista very useful method provided by the class, used to retrieve and remove the first element (head element) of the list. This method belongs toQueuepart of the interface,LinkedListimplements this interface, so it can be used as a queue.

Method Syntax:

public E poll()

Return Value:

  • If the list is not empty, returns the first element of the list
  • If the list is empty, returnsnull

Method Characteristics

Comparison with Similar Methods

In Java'sLinkedListthere are several similar methods that can be used to retrieve and remove the head element:

Method Behavior Description Behavior When List Is Empty
poll() Retrieves and removes the head element Returns null
remove() Retrieves and removes the head element Throws NoSuchElementException
pop() Retrieves and removes the head element (stack operation) Throws NoSuchElementException
pollFirst() Retrieves and removes the first element (same as poll()) Returns null

Time Complexity

poll()The time complexity of the method is O(1), because it only removes and returns the first element of the list without traversing the entire list.


Usage Examples

Basic Usage

Example

import java.util.LinkedList;

public class PollExample {
    public static void main(String[] args) {
        // Create a LinkedList
        LinkedList<String> fruits = new LinkedList<>();
       
        // Add elements
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
       
        System.out.println("Original list: " + fruits);  // Output: [Apple, Banana, Cherry]
       
        // Use the poll() method
        String firstFruit = fruits.poll();
       
        System.out.println("Removed element: " + firstFruit);  // Output: Apple
        System.out.println("Updated list: " + fruits);    // Output: [Banana, Cherry]
    }
}

Handling Empty Lists

Example

import java.util.LinkedList;

public class EmptyListExample {
    public static void main(String[] args) {
        LinkedList<String> emptyList = new LinkedList<>();
       
        // Use poll() on an empty list
        String result = emptyList.poll();
       
        System.out.println("Result: " + result);  // Output: null
    }
}

Use in Queue Operations

Example

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

public class QueueExample {
    public static void main(String[] args) {
        // Use LinkedList as a Queue
        Queue<Integer> queue = new LinkedList<>();
       
        // Enqueue operation
        queue.offer(10);
        queue.offer(20);
        queue.offer(30);
       
        System.out.println("Queue contents: " + queue);  // Output: [10, 20, 30]
       
        // Dequeue operation
        while (!queue.isEmpty()) {
            int num = queue.poll();
            System.out.println("Processed: " + num);
        }
       
        System.out.println("Final queue state: " + queue);  // Output: []
    }
}

Practical Application Scenarios

poll()The method is particularly useful in the following scenarios:

  1. Queue processing: When usingLinkedListas a queue,poll()is the standard dequeue operation.
  2. Task scheduling: Process a task list, taking the first task each time to execute.
  3. Breadth-first search: In graph or tree traversal algorithms, used to take the next node to process from the queue.
  4. Message processing: In a message queue, take out and process the next message.

Notes

  1. Empty list handling: Unlike theremove()method,poll()does not throw an exception when the list is empty, but instead returnsnull. This makes it more suitable for use when you are not sure whether the list is empty.
  2. Generic types: Ensure that the return value type is handled correctly to avoidClassCastException。
  3. Concurrent environment:LinkedListis not thread-safe; if used in a multi-threaded environment, synchronization issues need to be considered.

By mastering thepoll()method, you can more effectively useLinkedListas a queue and write cleaner, more robust Java code.

Java LinkedList Java LinkedList

Other Extensions