import java.util.ArrayList;
public class ArrayTest {
private static ArrayList<String> list = new ArrayList<String>();
public static void printList () {
System.out.println("Printing the list");
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) != null)
System.out.println(i + " => " + list.get(i));
}
}
public static void add(Integer index, String val) {
while(list.size() <= index)
list.add(null);
list.add(index, val);
}
public static void main(String[] args) {
ArrayTest.add(8, "cover");
ArrayTest.printList();
ArrayTest.add(6, "and");
ArrayTest.printList();
}
}
produces the following output
Printing the list
8 => cover
Printing the list
6 => and
9 => cover
The add(Integer index, String val) function adds an appropriate number of nulls to the list as a check to avoid any IndexOutOfBoundsException exceptions.
Can someone explain why does adding "and" to the list push "cover" a position further in the list ?