title: Why does HashMap resize() again, when specifying a precise capacity?
body: <p><strong>Code speaks more than words, so:</strong></p>
  
  <pre><code>final int size = 100;
  Map&lt;Integer, String&gt; m = new HashMap&lt;&gt;(size);
  for (int i = 0; i &lt; size; i++) m.put(i, String.valueOf(i));
  </code></pre>
  
  <p><strong>Why is the HashMap internally calling <code>resize()</code> <s><code>21</code></s> <code>2</code> times!</strong> (Credit to Andreas for identifying that the JVM uses HashMaps internally, 19 of the 21 cals were from other processes)</p>
  
  <p>Two <code>resize()</code> calls is still not acceptable for my application. I need to optimize this.</p>
  
  <p>If I am a new java developer, my first intuitive guess at what "capacity" means in the HashMap constructor is that it is the capacity for the number of elements that I (the consumer of  HashMap) am going to put into the Map. But this is not true.</p>
  
  <p>If I want to optimize my usage of HashMap so that it does not need to resize itself at all, then I need to know the internals of HashMap intimately enough to know exactly how sparse the HashMap bucket array needs to be. This is strange in my opinion. HashMap should implicitly do this for you. It is the whole point of encapsulation in OOP.</p>
  
  <p><em>Note: I have confirmed that resize() is the bottleneck for my applications use case, so that is why my goal is to reduce the number of calls to resize().</em></p>
  
  <p><strong>The question:</strong></p>
  
  <p>If I know the exact quantity of entries I am going to put into the map beforehand. What capacity do I chose, to prevent <strong><em>any</em></strong> extra calls <code>resize()</code> operations? Something like <code>size * 10</code>? I would also like some background on why <code>HashMap</code> is designed this way.</p>
  
  <p><em>Edit: I am getting asked a lot why this optimization is necassary. My application is spending a non-trivial amount of CPU time in hashmap.resize(). The hashmaps my application uses are initialized with a capacity equal to the number of elements that we put into it. Therefore, if we can reduce the resize() calls (by choosing a better initial capacity), then my application performance is improved.</em></p>