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

Last Updated : 03 Dec, 2024

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 `

// Java code to illustrate add(int index, E elements) import java.util.*;

public class ArrayListDemo { public static void main(String[] args) { // Creating List List l = new ArrayList(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:

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

**Exceptions:

Example of List add() Method

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

Java `

// 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 + " ");
    }
}

}

`