Java LinkedList element() Method Tutorial

In this section, we will learn what the LinkedList element() method is and how to use it in Java.

What is Java LinkedList element() Method?

The Java LinkedList element() method is used to get the first (head) element of a LinkedList object and return that as a result.

Note: this method does not remove the first element, however.

Java element() Method Syntax:

public E element()

element() Method Parameters:

The method does not take an argument.

element() Method Return Value:

The return value of this method is the first (head) element of the target LinkedList object.

element() Method Exceptions:

The method might throw one exception and that is:

NoSuchElementException: we get this exception if the target list is in fact empty!

Example: using LinkedList element() method

import java.util.LinkedList; 
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.addFirst("John");
        list.addFirst("Omid");
        list.addFirst("Jack");
        list.addFirst("Ellen");
        list.addFirst("Elon");

        System.out.println("The first element of the list is: "+list.element());
    }
}

Output:

The first element of the list is: Elon
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies