Java LinkedList getLast() Method Example

The getLast() method of java.util.LinkedList will return us the last element of the list. 

Signature

public E getLast() 

Retrieves the last element of the list. Throws java.lang.NoSuchElementException if the list is empty.

Example

The following example shows the usage of java.util.LinkedListgetLast() method.

import java.util.LinkedList;

public class GetLastMethodLinkedListExample {
	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 last element of the LinkedList
		System.out.println("Last element of the list is : "+list1.getLast());
		
	}
}

Output

Last element of the list is : Element3

Leave a Reply

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