Java LinkedList peekFirst() Method

Java LinkedList Java LinkedList


peekFirst()The method is a utility method provided by theLinkedListclass in Java, used to retrieve but not remove the first element of the linked list. If the linked list is empty, it returnsnull。

Method Syntax

public E peekFirst()

Method Features

  1. Non-destructive operation: UnlikepollFirst()orremoveFirst()some methods,peekFirst()it does not change the content of the linked list
  2. Fast access: Time complexity is O(1) because LinkedList directly maintains a reference to the head node
  3. Safe access: When the linked list is empty, it returnsnullinstead of throwing an exception

Usage Scenarios

peekFirst()This method is especially suitable for the following cases:

  1. When you need to check the head element of the queue but do not want to remove it
  2. To view the next element to process before consuming from the queue
  3. When implementing monitoring or logging functionality

Code Examples

Basic Usage Example

Example

import java.util.LinkedList;

public class PeekFirstExample {
    public static void main(String[] args) {
        LinkedList<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
       
        // View but do not remove the first element
        String firstFruit = fruits.peekFirst();
        System.out.println("First fruit: " + firstFruit);  // Output: First fruit: Apple
        System.out.println("LinkedList after peek: " + fruits);  // Output: [Apple, Banana, Cherry]
    }
}

Handling Empty Linked List Example

Example

import java.util.LinkedList;

public class EmptyListExample {
    public static void main(String[] args) {
        LinkedList<Integer> numbers = new LinkedList<>();
       
        // Safely handle an empty linked list
        Integer firstNumber = numbers.peekFirst();
        if (firstNumber == null) {
            System.out.println("The list is empty");
        } else {
            System.out.println("First number: " + firstNumber);
        }
    }
}

Comparison with Similar Methods

Method Name Function Behavior When the Linked List Is Empty Whether It Modifies the Linked List
peekFirst() View the first element returnsnull no
getFirst() Get the first element throwsNoSuchElementException no
pollFirst() Remove and return the first element returnsnull Yes
removeFirst() Remove and return the first element throwsNoSuchElementException Yes

Best Practices

  1. When unsure whether the linked list is empty, prefer usingpeekFirst()rather thangetFirst()
  2. If you need to both view and remove an element at the same time, consider usingpollFirst()to improve efficiency
  3. When using it in a concurrent environment,peekFirst()additional synchronization measures are required

FAQ

Q1: peekFirst()andpeek()What is the difference?

peek()andpeekFirst()The functionality in LinkedList is exactly the same,peek()it is provided to maintain consistency with the Queue interface.

Q2: WhypeekFirst()returnsnullinstead of throwing an exception?

This design allows more flexible handling of empty linked list situations, is especially suitable for queue operation scenarios, and avoids extra exception handling code.

Q3: Using it in a multi-threaded environmentpeekFirst()Is it safe?

LinkedList is not thread-safe. If you need to use it in a multi-threaded environment, you should consider usingCollections.synchronizedList()wrapping or switching toConcurrentLinkedDeque。

Java LinkedList Java LinkedList

other extensions