Press "Enter" to skip to content

LinkedList element() method with example in java

The element() method of LinkedList retrieves but does not remove the first element of this linked list. It throws NoSuchElementException if the linked list is empty.

Syntax

Object element()

Parameters

It doesn't take any parameter

Return Value

It returns the first element of this linked list.

Exception

throws NoSuchElementException if the linked list is empty.

Program 1

import java.util.LinkedList;

public class LinkedListElementExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
		System.out.println("First element in this linked-list: " + oddNumbers.element());

	}
}

Output

Linked List elements: [5, 7, 9, 11]
First element in this linked-list: 5

Program 2

import java.util.LinkedList;

public class LinkedListElementExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);

		oddNumbers.clear();
		System.out.println("First element in this linked-list: " + oddNumbers.element());

	}
}

Output

Linked List elements: [5, 7, 9, 11]
Exception in thread "main" java.util.NoSuchElementException
	at java.util.LinkedList.getFirst(LinkedList.java:244)
	at java.util.LinkedList.element(LinkedList.java:663)
	at LinkedListElementExample.main(LinkedListElementExample.java:18)

Be First to Comment

Leave a Reply

Your email address will not be published.