title: How does HashMap make sure the index calculated using hashcode of key is within the available range?
body: <p>I went through source code of HashMap and have a few questions. The PUT method takes the Key and Value and does </p>
  
  <ol>
  <li>the hashing function of the hashcode of the key.</li>
  <li><p>calculate bucket location for this pair using the hash obtained from the previous step</p>
  
  <pre><code>public V put(K key, V value) {
     int hash = hash(key.hashCode());
     int i = indexFor(hash, table.length);
     .....
  }
  
  
  static int hash(int h) {
     h ^= (h &gt;&gt;&gt; 20) ^ (h &gt;&gt;&gt; 12);
     return h ^ (h &gt;&gt;&gt; 7) ^ (h &gt;&gt;&gt; 4);
  }
  
  
  static int indexFor(int h, int length) {
     return h &amp; (length-1);
  }
  </code></pre></li>
  </ol>
  
  <p><strong>Example:</strong> </p>
  
  <ul>
  <li>Creating a HashMap with size 10.</li>
  <li>call put(k,v) three times and assume these 3 occupies bucket loc 7 ,8 and 9</li>
  <li>call put 4th K,V pair and following happens 
  <ul>
  <li>hash() is called with key.hashcode() and hash calculated</li>
  <li>indexFor is calculated based on hash</li>
  </ul></li>
  </ul>
  
  <p><strong>Question:</strong></p>
  
  <ol>
  <li>What if the calculated bucket location for the 4th k,v is out of the existing bounds? say location 11 ?</li>
  </ol>
  
  <p>Thanks in advance
  Akh </p>