Java LinkedList element() Method

Java LinkedList Java LinkedList


element()The method is, in Java,LinkedLista common method provided by the class, which is used to retrieve but not remove the first element (head element) of the linked list. This method inherits fromQueuethe interface, and is one of the basic methods of queue operations.

Method Declaration

public E element()

Return Value

Returns the first element of the linked list.

Exception

If the linked list is empty (i.e., contains no elements), this method throws NoSuchElementException.


Method Details

Basic Functionality

element()The main function of the method is toretrieve but not removethe first element of the linked list. Thispeek()is similar to the method, but there is a key difference: when the linked list is empty,peek()it will returnnull, whereaselement()it will throw an exception.

Comparison with Similar Methods

Method Name Function Description Behavior When the Linked List Is Empty
element() Retrieves but does not remove the first element ThrowsNoSuchElementException
peek() Retrieves but does not remove the first element Returnsnull
getFirst() Retrieves but does not remove the first element ThrowsNoSuchElementException
remove() Retrieves and removes the first element ThrowsNoSuchElementException
poll() Retrieves and removes the first element Returnsnull

Usage Examples

Example 1: Basic Usage

Example

import java.util.LinkedList;

public class ElementExample {
    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");
       
        // Use the element() method to get the first element
        String firstFruit = fruits.element();
        System.out.println("The first fruit is: " + firstFruit);
       
        // The LinkedList content remains unchanged
        System.out.println("LinkedList content: " + fruits);
    }
}

Output

第一个水果是: Apple
链表内容: [Apple, Banana, Cherry]

Example 2: Handling an Empty LinkedList

Example

import java.util.LinkedList;

public class EmptyListExample {
    public static void main(String[] args) {
        LinkedList<String> emptyList = new LinkedList<>();
       
        try {
            String item = emptyList.element();
            System.out.println(item);
        } catch (Exception e) {
            System.out.println("Exception occurred: " + e.getClass().getSimpleName());
            System.out.println("Error message: " + e.getMessage());
        }
    }
}

Output

发生异常: NoSuchElementException
错误信息: null

Best Practices

1. Check whether the linked list is empty

Before usingelement()the method, it is best to first check whether the linked list is empty to avoid exceptions:

Example

if (!myLinkedList.isEmpty()) {
    String firstElement = myLinkedList.element();
    // Handle the first element
} else {
    // Handle the empty linked list case
}

2. Consider using peek() instead

If you are not sure whether the linked list may be empty, and you do not want to handle exceptions, you can consider usingpeek()method:

Example

String firstElement = myLinkedList.peek();
if (firstElement != null) {
    // Handle the first element
} else {
    // Handle the empty linked list case
}

3. Performance Considerations

element()The time complexity of the method is O(1), because it only accesses the head node of the linked list and does not involve any traversal operations. This is the same asLinkedListthe other head-operation methods of the LinkedList (such asgetFirst()、peek()) in terms of performance characteristics.


Summary

LinkedListofelement()The method is a simple but practical tool for safely retrieving the first element of a linked list. Remember itspeek()key difference from the method, and choose the appropriate method based on your specific needs. In cases where you may encounter an empty linked list, either check in advance whether the linked list is empty, or consider usingpeek()method to avoid exception handling.

By using these methods appropriately, you can more effectively operate onLinkedListcollections and write more robust Java code.

Java LinkedList Java LinkedList

Other Extensions