Program to demonstrate how to add an element at specified index of java ArrayList object using add method in Java
package com.hubberspot.example;
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList Object of raw type
ArrayList list = new ArrayList();
// Add elements to it
list.add(3); // adds at index 0
list.add(2); // adds at index 1
list.add("String Object"); // adds at index 3
list.add(new Object()); // adds at index 4
System.out.println("ArrayList displayed using index : ");
System.out.println("----------------------------------------");
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
System.out.println("----------------------------------------");
// add elements at position already used
list.add(0, 1); // inserts at index 0
list.add(1, 2); // inserts at index 1
list.add(2, 5); // inserts at index 2
list.add(3, new Object()); // inserts at index 3
list.add(4, "new string"); // inserts at index 4
// Instead of overriding the values at indexes it shifts
// old values by one index higher
// Output below displays the truth ...
System.out.println();
System.out.println("ArrayList after using previous index : ");
System.out.println("----------------------------------------");
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
System.out.println("----------------------------------------");
}
}
Output of the program :
