I see that in the implementation of put method of HashMap class, the table bucket is got using int i = indexFor(hash, table.length); 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.
- How does it find the right bucket using the key? What if the bucket does not exist?
- How does it evaluate if it needs to add it in the same bucket or different bucket?
- 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!
Source 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<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((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 >= threshold) && (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<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }
 
     
    