Java LinkedList element() Method Example

The element() method of java.util.LinkedList will retrieve the head(first element) of the list and will not remove it.

Signature

public E element() 

Retrieves the head (first element) of this list. Throws “NoSuchElementException” if the list is empty.

Example

The following example shows the usage of element() method.

import java.util.LinkedList;

public class ElementMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList list1 = new LinkedList();
		
		// use add() method to add elements to the LinkedList
		list1.add("Element1");
		list1.add("Element2");
		list1.add("Element3");
		
		//Getting the head of the LinkedList
		System.out.println("First element of the list is : "+list1.element());
		
	}
}

Output

First element of the list is : Element1

Leave a Reply

Your email address will not be published. Required fields are marked *