title: How to initialize an ArrayList with a certain size and directly access its elements
body: <p>I was writing something that needs an arrayList of size n, so I did the following:</p>
  
  <pre><code>List&lt;Set&lt;Integer&gt;&gt; list = new ArrayList&lt;Set&lt;Integer&gt;(n);
  </code></pre>
  
  <p>And when I was trying to access an element of the list e.g.</p>
  
  <pre><code>list.get(someValue that is &lt;n)
  </code></pre>
  
  <p>I got arrayList out of bound exception, so I guess putting a n there doesn't really help you initialize the list, but just pre-allocate the space.</p>
  
  <p>Is there a way to do the initialization after which there are actually null or objects in each slot?</p>
  
  <p>I end up using a for loop and adding n empty set and then index into the list.</p>
  
  <p>Is there a better way TO INITIALIZE AN ARRAYLIST IF THE SIZE IS KNOWN IN ADVANCE?</p>
  
  <p>Please know what I'm asking before saying this is a duplicate. </p>
  
  <p>Hope my question is clear.</p>
  
  <p>Thanks in advance.</p>
  
  <p>Some of you think what I tried to do is meaningless. This happens when I tried to solve a bucket sort related problem where the index of the set I tried to access in the array is known. So for example, I want to add some elements to the set at position 1, 3, 2, 4... then it would be convenient if I can just get the set at position 1, 3, 2, 4...   </p>