LinkedList element() Method in Java (original) (raw)

Last Updated : 16 Dec, 2024

In Java, the **element() method of the LinkedList class is used to retrieve the first element in the list without removing it. The first element of the LinkedList is known as the **head.

**Example 1: Here, we use the **element() method **to retrieve the first element of the LinkedList of Integers, _without removing it.

Java `

// Demonstrate element() method // for Integer value import java.util.LinkedList;

class Geeks { public static void main(String[] args) { LinkedList l = new LinkedList<>();

    // Use add() to insert  
    // elements in the list
    l.add(10);
    l.add(20);
    l.add(30);
    System.out.println("" + l);
  
    // getting the head of list 
    // using element() method 
    System.out.println("" + l.element());
}

}

`

Syntax of Java LinkedList element() Method

public E element()

**Return Value: This method returns the **head of the list.

**Example 2: Here, **element() method throws NoSuchElementException when we **try to get the head of an empty LinkedList.

Java `

// Throws Exception import java.util.LinkedList; import java.util.NoSuchElementException;

class Geeks { public static void main(String[] args) { LinkedList l = new LinkedList<>();

    l.add("A");
    l.add("B");
    l.add("C");

    System.out.println("" + l);

    // Displaying the head of List
    System.out.println("Head: "
                       + l.element());

    // Remove all elements 
    // from the List
    l.clear();
    try {
        // Try to get the head of 
        // an empty LinkedList
        System.out.println(
            "Head of an Empty Linked List: "
            + l.element());
    }
    catch (Exception e) {
        System.out.println("Exception: " + e);
    }
}

}

`

Output

[A, B, C] Head: A Exception: java.util.NoSuchElementException