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:
- index: This parameter specifies the index at which we the given element is to be inserted.
- element: This parameter specifies the element to insert in the list.
Return Value: Â Boolean and it returns true if the object is added successfully.Â
Exceptions:
- UnsupportedOperationException – It throws this exception if the add() operation is not supported by this list.
- ClassCastException – It throws this exception if the class of the specified element prevents it from being added to this list.
- NullPointerException – It throws this exception if the specified element is null and this list does not permit null elements.
- IllegalArgumentException – It throws this exception if some property of this element prevents it from being added to this list.
Below programs illustrate the List.add(int index, E element) method:Â
Program 1:Â
Java
// 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 + " " );         }     } } |
Hello Geeks For Geeks
Program 2:Â
Java
// 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 + " ");         }     } } |
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.