title: put method of Hashmap
body: <p>I see that in the implementation of put method of HashMap class, the table bucket is got using <code>int i = indexFor(hash, table.length);</code> and then it adds an entry to that bucket - 'i' if the hashcode and the key are not equal. If they are equal, the old value is replaced.</p>
  
  <ul>
  <li>How does it find the right bucket using the key? What if the bucket does not exist?</li>
  <li>How does it evaluate if it needs to add it in the same bucket or different bucket?</li>
  <li>What happens when the hash codes are same and keys are different? If the hashcodes are same, then the entry should be in the same bucket but I do not see that in the code of put method!</li>
  </ul>
  
  <p>Source code:</p>
  
  <pre><code>public V put(K key, V value) {
      if (table == EMPTY_TABLE) {
          inflateTable(threshold);
      }
      if (key == null)
          return putForNullKey(value);
      int hash = hash(key);
      int i = indexFor(hash, table.length);
      for (Entry&lt;K,V&gt; e = table[i]; e != null; e = e.next) {
          Object k;
          if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k))) {
              V oldValue = e.value;
              e.value = value;
              e.recordAccess(this);
              return oldValue;
          }
      }
  
      modCount++;
      addEntry(hash, key, value, i);
      return null;
  }
  
  
  void addEntry(int hash, K key, V value, int bucketIndex) {
      if ((size &gt;= threshold) &amp;&amp; (null != table[bucketIndex])) {
          resize(2 * table.length);
          hash = (null != key) ? hash(key) : 0;
          bucketIndex = indexFor(hash, table.length);
      }
  
      createEntry(hash, key, value, bucketIndex);
  }
  
  void createEntry(int hash, K key, V value, int bucketIndex) {
          Entry&lt;K,V&gt; e = table[bucketIndex];
          table[bucketIndex] = new Entry&lt;&gt;(hash, key, value, e);
          size++;
      }
  </code></pre>