Add an item to a specific index in ArrayList in Java

This java example shows how to insert an item into a specific index in Java using the method add(int index, Object o). Note that this method does not overwrite the previously inserted elements, but they are all offset by one square to the right.

import java.util.ArrayList; 

public class ArrayListAddIndex{

public static void main(String[] args) {

// Create an ArrayList
ArrayList arraylist = new ArrayList();

//add strings to ArrayList
arraylist.add("a");
arraylist.add("b");
arraylist.add("c");
arraylist.add("d");
arraylist.add("e");

System.out.println("ArrayList before ");
for(String e:arraylist)
System.out.println(e);

arraylist.add(2, "new element");

System.out.println("ArrayList after ");
for(String e:arraylist)
System.out.println(e);
}
}
Runtime:

ArrayList before 
a
b
c
d
e
ArrayList after
a
b
new element< br />c
d
e