YouTip LogoYouTip

Java Linkedlist Peek

[![Image 1: Java LinkedList](#) Java LinkedList](#) * * * `peek()` method is a very useful method provided by the `LinkedList` class in Java. It is used to retrieve but not remove the first element (head element) of the linked list. This method belongs to the operations of the `Queue` interface, which `LinkedList` implements. **Method Syntax**: public E peek() **Return Value**: * If the linked list is not empty, returns the first element of the linked list * If the linked list is empty, returns `null` * * * ## Method Features ### Non-destructive Operation `peek()` method only "peeks" at the first element of the linked list without removing it from the list. This is different from `poll()` or `remove()` methods, which remove elements. ### Null-safe When the linked list is empty, `peek()` returns `null` instead of throwing an exception, making it safer than `getFirst()` or `element()` in certain scenarios. ### Time Complexity Since `LinkedList` is implemented as a doubly linked list, the time complexity of `peek()` is O(1), as it only needs to access the head node. * * * ## Usage Examples ### Basic Example ## Example import java.util.LinkedList; public class PeekExample { public static void main(String[] args){ LinkedList fruits =new LinkedList(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Use peek() to view the first element String firstFruit = fruits.peek(); System.out.println("First fruit: "+ firstFruit);// Output: First fruit: Apple System.out.println("LinkedList after peek(): "+ fruits);// Output: [Apple, Banana, Cherry] } } ### Empty List Example ## Example import java.util.LinkedList; public class EmptyListPeek { public static void main(String[] args){ LinkedList numbers =new LinkedList(); Integer firstNumber = numbers.peek(); System.out.println("First number: "+ firstNumber);// Output: First number: null } } * * * ## Comparison with Other Similar Methods ### peek() vs getFirst() | Method | Empty List Behavior | Throws Exception | | --- | --- | --- | | peek() | Returns null | No | | getFirst() | Throws NoSuchElementException | Yes | ### 4.2 peek() vs element() | Method | Empty List Behavior | Throws Exception | | --- | --- | --- | | peek() | Returns null | No | | element() | Throws NoSuchElementException | Yes | ### 4.3 peek() vs poll() | Method | Removes Element | Empty List Behavior | | --- | --- | --- | | peek() | No | Returns null | | poll() | Yes | Returns null | * * * ## Practical Application Scenarios ### Message Queue Processing When processing message queues, we often need to view the message at the head of the queue without removing it: ## Example LinkedList messageQueue =new LinkedList(); // ... Add messages to the queue // Check but do not remove the first message Message nextMessage = messageQueue.peek(); if(nextMessage !=null&& nextMessage.isHighPriority()){ // Handle high priority message } ### Task Scheduling System In a task scheduling system, `peek()` can be used to check the next task to execute: ## Example LinkedList taskQueue =new LinkedList(); // ... Add tasks to the queue Task nextTask = taskQueue.peek(); if(nextTask !=null&& nextTask.isReadyToExecute()){ // Execute task } ### Browser History Simulate browsing to view the most recently visited page without removing it from history: ## Example LinkedList browserHistory =new LinkedList(); // ... Add visit records String lastVisited = browserHistory.peek(); System.out.println("Most recently visited page: "+ lastVisited); * * * ## Notes 1. **Null Handling**: Since `peek()` may return `null`, you should perform a null check on the return value before using it to avoid `NullPointerException`. 2. **Concurrent Environment**: `LinkedList` is not thread-safe. If using `peek()` in a multi-threaded environment, additional synchronization measures are required. 3. **Performance Consideration**: Although `peek()` operation itself is O(1), if it is frequently called along with other operations, you may need to consider more efficient data structures. 4. **Comparison with Stack Operations**: When `LinkedList` is used as a stack, `peek()` views the first element (stack top), which is consistent with the `peek()` method behavior of the `Stack` class. [![Image 2: Java LinkedList](#) Java LinkedList](#)
← Java Linkedlist PeekfirstJava Linkedlist Indexof β†’