Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you don't like using your own loop and the list <code>add</code> method directly then there is another way. Create your <code>ArrayList</code> with the number of elements you want it directly like this:</p> <pre><code>final int MAX_ELEMENTS = 1000; List&lt;Integer&gt; myList = new ArrayList&lt;Integer&gt;( Collections.&lt;Integer&gt;nCopies(MAX_ELEMENTS, null)); </code></pre> <p>Or, if you already have a list that you want to expand the size by <code>n</code> elements:</p> <pre><code>myList.addAll(Collections.&lt;Integer&gt;nCopies(n, null)); </code></pre> <p>(Note, I assumed here that the list would be holding <code>Integer</code> objects, but you can change this to your custom type. If you are working with raw/pre-Java 5 types then just drop the generic declarations.)</p> <p>As for your actual question: capacity != contents. An ArrayList internally has both a physical array and a count of what is actually in it. Increasing the capacity, changes the internal array so it can hold that many elements, however, the count does not change. You need to add elements to increase that count.</p> <p>On the other hand, if you are just trying to set specific elements and know the maximum that you want to use, why not use an array directly? If you then need to pass this array to an API that takes <code>List</code>s, then use <code>Arrays.asList</code>. The other classes could still change contents of your backing array but it would not be able to increase the size or capacity of it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload