Java LinkedList peek() Method
peek()The method is, in Java,LinkedLista very useful method provided by the class. It is used to retrieve but not remove the first element (head element) of the linked list. This method belongs toQueuethe operations of the interface,LinkedListand LinkedList implements this interface.
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
null
Method Features
Non-destructive operation
peek()The method only "views" the first element of the linked list without removing it. This is different frompoll()orremove()the remove() method, which removes the element.
Null safety
When the linked list is empty,peek()peek() returns nullnulland does not throw an exception, which makes it moregetFirst()orelement()safer than element() in some scenarios.
Time complexity
SinceLinkedListLinkedList is implemented based on a doubly linked list,peek()the time complexity of the method is O(1), because it only needs to access the head node.
Usage examples
Basic example
Example
public class PeekExample {
public static void main(String[] args) {
LinkedList<String> 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 linked list example
Example
public class EmptyListPeek {
public static void main(String[] args) {
LinkedList<Integer> 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 | Behavior on empty linked list | Throws exception |
|---|---|---|
| peek() | Returns null | no |
| getFirst() | Throws NoSuchElementException | Yes |
4.2 peek() vs element()
| Method | Behavior on empty linked list | Throws exception |
|---|---|---|
| peek() | Returns null | no |
| element() | Throws NoSuchElementException | Yes |
4.3 peek() vs poll()
| Method | Whether it removes elements | Behavior on empty linked list |
|---|---|---|
| peek() | no | Returns null |
| poll() | Yes | Returns null |
Practical application scenarios
Message queue processing
When processing a message queue, we often need to view the message at the head of the queue without removing it:
Example
// ... add messages to the queue
// Check but do not remove the first message
Message nextMessage = messageQueue.peek();
if (nextMessage != null && nextMessage.isHighPriority()) {
// Process high-priority messages
}
Task scheduling system
In a task scheduling system,peek()peek() can be used to check the next task to execute:
Example
// ... add tasks to the queue
Task nextTask = taskQueue.peek();
if (nextTask != null && nextTask.isReadyToExecute()) {
// Execute the task
}
Browser history
Simulate viewing the most recently visited page in a browser without removing it from history:
Example
// ... add visit records
String lastVisited = browserHistory.peek();
System.out.println("Most recently visited page: " + lastVisited);
Notes
Null value handling: Since
peek()peek() may return nullnull, you should perform a null check before using the return value to avoidNullPointerException。Concurrent environment:
LinkedListLinkedList is not thread-safe. If it is used in a multi-threaded environment,peek(), additional synchronization measures are required.Performance considerations: Although
peek()the operation itself is O(1), if it is called frequently along with other operations, you may need to consider more efficient data structures.Comparison with stack operations: When
LinkedListLinkedList is used as a stack,peek()peek() views the first element (top of the stack), which is the same asStackthe Stack class'speek()peek() method behavior.
Java LinkedList