In Java, the add(int index, E element) method of the ArrayList class allows you to insert an element at a specific index. When you use this method, the following happens:
-
Shifting Elements: The elements that are currently at and after the specified index are shifted to the right (i.e., their indices are increased by one) to make room for the new element.
-
Inserting the Element: The specified element is then inserted at the given index.
Here’s an example of how to use the add method to insert an element at a specific index in an ArrayList:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("Before insertion: " + list);
// Insert "Orange" at index 1
list.add(1, "Orange");
System.out.println("After insertion: " + list);
}
}
Output:
Before insertion: [Apple, Banana, Cherry]
After insertion: [Apple, Orange, Banana, Cherry]
In this example, "Orange" is inserted at index 1, and "Banana" is shifted to index 2.
