Java Utility Library

Java LinkedList - addFirst() Method



The java.util.LinkedList.addFirst() method is used to insert the specified element at the start of the list.

Syntax

public void addFirst(E element)

Here, E is the type of element maintained by the container.


Parameters

element Specify element which need to be inserted in the list.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.LinkedList.addFirst() method is used to insert the specified element at the start of the list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedlist
    LinkedList<Integer> MyList = new LinkedList<Integer>();

    //populating linkedlist using addFirst method
    MyList.addFirst(10);
    MyList.addFirst(20);
    MyList.addFirst(30);

    //printing linkedlist
    System.out.println("MyList contains: " + MyList);   
  }
}

The output of the above code will be:

MyList contains: [30, 20, 10]

❮ Java.util - LinkedList