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<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 + " ");
}
}
}
Hello Geeks For GeeksSyntax 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:
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 + " ");
}
}
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4