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.
Implementation:
// Java code to illustrate add(int index, E elements)
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
// Creating List
List<String> l = new ArrayList<String>(5);
// Adding element in List
l.add("Geeks");
l.add("For");
l.add("Geeks");
// use add() method to initially
// add elements in the list
l.add(0, "Hello");
// Printing elements
for (String str : l) {
System.out.print(str + " ");
}
}
}
Output
Hello Geeks For Geeks
Syntax of Method
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.
Example of List add() Method
Below programs illustrate the List.add(int index, E element) method:
// Java code to illustrate add(int index, E elements)
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
// Create an empty list
List<Integer> l = new ArrayList<Integer>(5);
// Adding Elements in List
l.add(10);
l.add(20);
l.add(30);
// Add a new 25 at index 2 and print true
// if the element is added successfully
System.out.println(l.add(2, 25));
// Prints element of List
for (Integer num : l) {
System.out.print(num + " ");
}
}
}
Output
10 20 25 30