Java Utility Library

Java LinkedList - add() Method



The java.util.LinkedList.add() method is used to insert the specified element at specified index in the list. The method shifts the current element at the specified position (if any) and any subsequent elements to the right by adding one to their indices. Addition of new element results into increasing the list size by one.

Syntax

public void add(int index, E element)

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


Parameters

index Specify index number at which new element need to be inserted in the list.
element Specify element which need to be inserted in the list.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if the index is out of range i.e., (index < 0 || index > size()).

Example:

In the example below, the java.util.LinkedList.add() method is used to insert the specified element at specified position in 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
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    //inserting new element in the linkedlist
    MyList.add(1,100);
    System.out.println("MyList contains: " + MyList); 

    //inserting new element in the linkedlist
    MyList.add(0,500);
    System.out.println("MyList contains: " + MyList);    
  }
}

The output of the above code will be:

MyList contains: [10, 100, 20, 30]
MyList contains: [500, 10, 100, 20, 30]

❮ Java.util - LinkedList