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
import java.io.*;
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args)
{
List<String> list = new ArrayList<String>( 5 );
list.add( "Geeks" );
list.add( "For" );
list.add( "Geeks" );
list.add( 0 , "Hello" );
for (String str : list) {
System.out.print(str + " " );
}
}
}
|
OutputHello Geeks For Geeks
Program 2:
Java
import java.io.*;
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>( 5 );
list.add( 10 );
list.add( 20 );
list.add( 30 );
System.out.println(list.add( 2 , 25 ));
for (Integer num : list) {
System.out.print(num + " ");
}
}
}
|
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.