title: Adding elements to ArrayList in java
body: <pre><code>import java.util.ArrayList;
  
  public class ArrayTest {
  
      private static ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
  
  
      public static void printList () {
          System.out.println("Printing the list");
          for (int i = 0; i &lt; list.size(); i++)
          {
              if (list.get(i) != null)
                  System.out.println(i + " =&gt; " + list.get(i));
          }   
      }
  
      public static void add(Integer index, String val) {
          while(list.size() &lt;= 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();
      }   
  
  }
  </code></pre>
  
  <p>produces the following output</p>
  
  <pre><code>Printing the list
  8 =&gt; cover
  Printing the list
  6 =&gt; and
  9 =&gt; cover
  </code></pre>
  
  <p>The <code>add(Integer index, String val)</code> function adds an appropriate number of nulls to the list as a check to avoid any <code>IndexOutOfBoundsException</code> exceptions.
  Can someone explain why does adding "and" to the list push "cover" a position further in the list ?</p>