【816、说下 HashMap put 源码?】

110 阅读1分钟
// 伪代码:简化版的 HashMap.put() 方法

// put方法用于将键值对(key-value)添加到HashMap中
public V put(K key, V value) {
    // 计算哈希值,用于确定存储位置
    int hash = hash(key);

    // 通过哈希值计算索引位置,找到对应的桶(bucket)
    int index = indexFor(hash, table.length);

    // 遍历对应的桶,查找是否有已存在的key
    for (Entry<K,V> e = table[index]; e != null; e = e.next) {
        K k;
        if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
            // 如果找到已存在的key,则更新对应的value,并返回旧的value
            V oldValue = e.value;
            e.value = value;
            return oldValue;
        }
    }

    // 没有找到已存在的key,创建一个新的Entry对象,并添加到对应的桶中
    modCount++; // 记录结构修改的次数,用于检测并发修改
    addEntry(hash, key, value, index);
    return null; // 返回null表示之前没有对应的key
}

// 计算哈希值
static int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

// 根据哈希值和数组长度计算索引位置
static int indexFor(int h, int length) {
    return h & (length-1);
}

// 将新的Entry添加到对应的桶中
void addEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    if (size++ >= threshold) {
        // 如果当前存储的键值对数量超过阈值,则进行扩容
        resize(2 * table.length);
    }
}