Java LinkedList offerFirst(E e) Method Example

Unlike offer(E e) method of java.util.LinkedList class which inserts the specified element to the tail of the list. offerFirst(E e) method will add the specified element to the front of the list

Signature

public boolean offerFirst(E e)

Adds the specified element to the front of the list and will return true if the insertion is successful.

Example

The following example shows the usage of offerFirst(e) method.

import java.util.Iterator;
import java.util.LinkedList;

public class OfferFirstMethodLinkedListExample {
	public static void main(String args[])
	{
		// Create LinkedList object
        LinkedList list1 = new LinkedList();
        
        //adding elements to list1
        list1.add("String 1");
        list1.add("String 2");
        list1.add("String 3");
        list1.add("String 4");
      
        //addding element to the front of the list
        boolean insertion= list1.offerFirst("String 88");
        
        //printing all the values of the LinkedList
        System.out.println("**Contents of the list**");
        Iterator iterator = list1.iterator();
        while(iterator.hasNext())
        {
        	System.out.println(iterator.next());
        }
        
        System.out.println("Is the insertion successful ?? "+insertion);
	}
}

Output

**Contents of the list**
String 88
String 1
String 2
String 3
String 4
Is the insertion successful ?? true

Leave a Reply

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