Java LinkedList removeFirst() Example

We have already learnt about poll() and pollFirst(),remove() methods of java.util.LinkedList class which will get us the first element(head) of the list and at the same time it will remove that element from the list. Our removeFirst() method also performs the same operation as poll(), pollFirst() and remove() does, retrieves and removes he first element of the list.

Signature

public E removeFirst()

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

Example

The following example shows the usage of LinkedList.removeFirst() method.

import java.util.LinkedList;

public class RemoveFirstMethodLinkedListExample {
	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");

		//Printing the elements of the LinkedList list1
		System.out.println("**Elements of the list1 before removeFirst**");
		for(String temp:list1)
		{
			System.out.println(temp);
		}
		
		//Removing the head of the list
		list1.removeFirst();
		
		//Printing the elements of the LinkedList list1
		System.out.println("**Elements of the list1 after removeFirst**");
		for(String temp:list1)
		{
			System.out.println(temp);
		}
	}
}

Output

**Elements of the list1 before removeFirst**
Element1
Element2
Element3
**Elements of the list1 after removeFirst**
Element2
Element3

Leave a Reply

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