Sunday, December 29, 2024
Google search engine
HomeLanguagesJavaList add(int index, E element) method in Java

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:

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


Output

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


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.

RELATED ARTICLES

Most Popular

Recent Comments