Java LinkedList addFirst(E e) Method Example

We know add(E e) method will add the specified element to the end of the LinkedList whereas addFirst(E e)  of java.util.LinkedList class will add specified element at the beginning of the LinkedList.

Signature

public boolean addFirst(E e)

This method appends the specified element to the beginning of this list.e is the element which will be appended and will return true on successful insertion.

Example

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

import java.util.LinkedList;

public class AddFirstMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the linkedlist
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		
		//adding new element using addFirst() 
		l.addFirst("Element4");
		
		//Printing the elements of the list
		System.out.println("Elements of the list");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

Elements of the list
Element4
Element1
Element2
Element3

Leave a Reply

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