Open In App

List add(int index, E element) method in Java

The add(int index, E ele) method of List interface in Java is used to insert the specified element at the given index in the current list. Syntax:

public add(int index, E element)

Parameter: This method accepts two parameters as shown in the above syntax:



Return Value:  Boolean and it returns true if the object is added successfully. 

Exceptions:



Below programs illustrate the List.add(int index, E element) method: 

Program 1: 




// Java code to illustrate add(int index, E elements)
 
import java.io.*;
import java.util.*;
 
public class ArrayListDemo {
    public static void main(String[] args)
    {
        // create an empty list with an initial
        // capacity
        List<String> list = new ArrayList<String>(5);
 
        // use add() method to initially
        // add elements in the list
        list.add("Geeks");
        list.add("For");
        list.add("Geeks");
       
        // Add a new element at index 0
        list.add(0, "Hello");
       
        // prints all the elements available in list
        for (String str : list) {
            System.out.print(str + " ");
        }
    }
}

Output
Hello Geeks For Geeks 

Program 2: 




// Java code to illustrate add(int index, E elements)
import java.io.*;
import java.util.*;
 
public class ArrayListDemo {
    public static void main(String[] args)
    {
 
        // create an empty list with an initial capacity
        List<Integer> list = new ArrayList<Integer>(5);
 
        // use add() method to initially
        // add elements in the list
        list.add(10);
        list.add(20);
        list.add(30);
 
        // Add a new  25 at index 2 and print true if the element is added successfully
        System.out.println(list.add(2, 25));
 
        // prints all the elements available in list
        for (Integer num : list) {
            System.out.print(num + " ");
        }
    }
}

Output:
10 20 25 30

The Time Complexity of add( E element)) is O(1).
The Time Complexity of add(int index, E element)) is O(n) i.e linear.


Article Tags :