Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java LinkedList element() method
Syntax and Examples


Introduction

The element() method in Java's LinkedList class is a handy tool for retrieving the first element of the list without removing it. Think of it like peeking at the front of a queue – you want to see what’s there, but don’t want to take it out.

Syntax


public E element()

Parameters

Parameter Description
None This method doesn't accept any parameters.

Return Value

The element() method returns the first element of the list (the head). If the list is empty, it throws a NoSuchElementException.

Examples

Example 1: Retrieving the First Element

This example demonstrates how to retrieve the first element from a LinkedList. It's a simple way to inspect what’s at the head of your list.


import java.util.*;

public class LinkedListElementExample1 {
    public static void main(String[] args) {
        LinkedList<String> myList = new LinkedList<>(
                Arrays.asList("apple", "banana", "cherry")
        );

        try {
            String firstElement = myList.element();
            System.out.println("First element: " + firstElement);
        } catch (NoSuchElementException e) {
            System.out.println("The list is empty.");
        }
    }
}

First element: apple

Explanation: We create a LinkedList named myList and add three strings to it. Then, we use the element() method to get the first element (which is “apple”). The output confirms that we retrieved the expected value.

Example 2: Handling an Empty List

This example shows how to handle a potential NoSuchElementException when attempting to retrieve an element from an empty list. It's important for robust code, especially when you might not always know if the list will contain elements.


import java.util.*;

public class LinkedListElementExample2 {
    public static void main(String[] args) {
        LinkedList<Integer> emptyList = new LinkedList<>();

        try {
            Integer firstElement = emptyList.element();
            System.out.println("First element: " + firstElement);
        } catch (NoSuchElementException e) {
            System.out.println("The list is empty, cannot retrieve the element.");
        }
    }

The list is empty, cannot retrieve the element.

Explanation: We create an empty LinkedList called emptyList. When we try to call element() on this empty list, a NoSuchElementException is thrown. The try-catch block catches this exception and prints an appropriate error message.

Example 3: Using with Generic Types

This demonstrates the versatility of the element() method by using it with different generic types – in this case, doubles.


import java.util.*;

public class LinkedListElementExample3 {
    public static void main(String[] args) {
        LinkedList<Double> myDoubles = new LinkedList<>(
                Arrays.asList(1.1, 2.2, 3.3)
        );

        try {
            Double firstDouble = myDoubles.element();
            System.out.println("First double: " + firstDouble);
        } catch (NoSuchElementException e) {
            System.out.println("The list is empty.");
        }
    }

First double: 1.1

Explanation: We create a LinkedList of Doubles and use the element() method to retrieve the first element, which is 1.1.


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M