Java LinkedList removeLast() Method Example

We have already learnt about pollLast() method of java.util.LinkedList class which will get us the last element(tail) of the list and at the same time it will remove that element from the list. Our removeLast() method also does the same retrieves and removes the last element from the list

Signature

public E removeLast()

This method retrieves and removes the tail of the list and will throw NoSuchElementException if the list is empty.

Example

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

import java.util.LinkedList;

public class RemoveLastLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the list
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		l.add("Element4");
		l.add("Element5");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list before removeLast**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		//Removing tail of the list
		System.out.println("Element removed from the list \""+l.removeLast()+"\"");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list after removeLast**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

**Elements of the list before removeLast**
Element1
Element2
Element3
Element4
Element5
Element removed from the list "Element5"
**Elements of the list after removeLast**
Element1
Element2
Element3
Element4

Leave a Reply

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