title: ArrayList initial capacity and IndexOutOfBoundsException
body: <p>Consider this sample code:</p>
  
  <pre><code>List&lt;String&gt; myList = new ArrayList&lt;String&gt;(7);
  myList.add(5, "Hello");
  myList.removeAll(Collections.singleton(null));
  
  System.out.println(myList.size() + " objects:" );
  for (String s : myList) {
      System.out.println("\t" + s);
  }
  </code></pre>
  
  <p><code>myList</code> is initialized with an initial capacity of 7, then the next line attempts to add the String "Hello" at position 5. This throws an IndexOutOfBoundsException:</p>
  
  <blockquote>
    <p>Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 0</p>
  </blockquote>
  
  <p>I looked over <a href="https://stackoverflow.com/questions/4172480/whats-meant-by-parameter-int-initial-capacity-in-an-arraylist">this question</a> about what "initial capacity" means in terms of an ArrayList. I understand that this particular constructor is allocating room for 7 String elements, and if we try to add 8 elements to the list it'll have to allocate more room. </p>
  
  <p>What I <em>don't</em> understand is why it doesn't create an "empty" list of size 7, with null values at each index, similar to what would happen if we declared <code>String[] myArray = new String[7]</code>. I recall learning that ArrayList is Java's implementation of a dynamic array, so I'd expect a similar sort of behavior. If I don't actually have space for 7 Strings allocated when I declare <code>new ArrayList&lt;String&gt;(7)</code>, what is actually happening?</p>