title: ArrayList index out of bounds exception
body: <p>Recently while using arrayList I found a weird issue. I want to keep 2 elements in the arraylist and would like to keep object1 in element 0 and object2 in element1. </p>
  
  <p>I am deciding this in a loop. </p>
  
  <p>When it happens to add the first element its throwing indexOutofBounds. As per java doc as the index is greater than size its doing this. </p>
  
  <pre><code>public static void main(String[] args) 
      {
          ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
          list.add(1,"SECONDITEM"); // throwing  due to size is not set
          list.add(0,"FIRSTITEM");
  
          int postn=0;
          for(String item:list){
  
              System.out.println("Position "+postn+" :"+item);
              postn++;
          }
      }
  </code></pre>
  
  <p>Then I tried to setup other items as placeholder in 0,1 element and tried to do same</p>
  
  <pre><code>    public static void main(String[] args) 
      {
          ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
          list.add(0,"x");
          list.add(1,"y");
  
          list.add(1,"SECONDITEM");
  
          list.add(0,"FIRSTITEM");
  
          int postn=0;
          for(String item:list){
  
              System.out.println("Position "+postn+" :"+item);
              postn++;
          }
      }
  
      Output:
      Position 0 :FIRSTITEM
      Position 1 :x
      Position 2 :SECONDITEM
      Position 3 :y
  </code></pre>
  
  <h2>How to get over this issue. One way I found is to remove the element in the index and add the element. Is there a better option.</h2>
  
  <pre><code>public static void main(String[] args) 
      {
          ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();
          list.add(0,"x");
          list.add(1,"y");
          list.remove(1);
          list.add(1,"SECONDITEM");
          list.remove(0);
          list.add(0,"FIRSTITEM");
  
          int postn=0;
          for(String item:list){
  
              System.out.println("Position "+postn+" :"+item);
              postn++;
          }
      }
  
      Position 0 :FIRSTITEM
      Position 1 :SECONDITEM
  </code></pre>