Java HashMap 源码分析

19 阅读6分钟

Java HashMap 源码分析

一、整体结构

HashMap
├── 底层结构:Node[] table(数组 + 链表/红黑树)
├── 核心参数:capacity、loadFactor、threshold、size
├── 节点类型:Node(链表)、TreeNode(红黑树,JDK 8+)
└── 关键方法:hash()、put()、get()、resize()

数据结构示意

table 数组
┌─────┬─────┬─────┬─────┬─────┐
│  0123  │ ... │
└──┬──┴──┬──┴──┬──┴──┬──┴─────┘
   │     │     │     │
   ▼     ▼     ▼     ▼
 Node  Node  Node  Node
   │     │     │     │
   ▼     ▼     ▼     ▼
 Node  null  Node  TreeNode
   │           │     │
   ▼           ▼     ▼
 null        Node  Node
                 (红黑树)

二、核心字段与常量

// 默认初始容量 16,必须是 2 的幂
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;

// 默认负载因子 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;

// 链表转红黑树阈值(桶中元素数)
static final int TREEIFY_THRESHOLD = 8;

// 红黑树退化为链表阈值
static final int UNTREEIFY_THRESHOLD = 6;

// 最小树化容量(table 长度小于此值先扩容而非树化)
static final int MIN_TREEIFY_CAPACITY = 64;

// 存储键值对的数组
transient Node<K,V>[] table;

// 键值对数量
transient int size;

// 扩容阈值 = capacity * loadFactor
int threshold;

// 负载因子
final float loadFactor;

三、hash():扰动函数

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

原理说明

步骤逻辑说明
1key.hashCode()获取 key 的 32 位哈希值
2h >>> 16高 16 位右移,与低 16 位对齐
3h ^ (h >>> 16)高 16 位与低 16 位异或,混合高位信息到低位

目的:减少低位碰撞。若直接用 hashCode % capacity,当 capacity 较小时,只有 hashCode 的低几位参与运算,高位信息丢失,碰撞概率高。扰动后高位参与运算,分布更均匀。


四、索引计算

// 计算桶下标
int index = (n - 1) & hash;

为什么用 (n-1) & hash 而非 hash % n?

方式说明
(n-1) & hashn 为 2 的幂时,等价于 hash % n,但位运算更快
前提capacity 必须为 2 的幂,保证 (n-1) 的二进制全为 1,如 n=16 时 (n-1)=15=0b1111& 操作等价于取 hash 的低 4 位

五、put():插入流程

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab;
    Node<K,V> p;
    int n, i;
    // 步骤1:table 为空则初始化
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 步骤2:计算桶下标,若桶为空则直接放入
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e;
        K k;
        // 步骤3:桶首节点 key 相同,直接覆盖
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 步骤4:若为红黑树,走树插入
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        // 步骤5:链表遍历
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 步骤6:链表长度 ≥ 8 且 table 长度 ≥ 64,树化
                    if (binCount >= TREEIFY_THRESHOLD - 1)
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 步骤7:找到已存在的 key,覆盖 value
        if (e != null) {
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 步骤8:size 超过 threshold 则扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

步骤说明

步骤逻辑说明
1resize()table 为空或长度为 0 时初始化,默认 capacity=16
2tab[i] = newNode(...)桶为空,直接放入新节点
3p.hash == hash && key.equals(k)桶首节点 key 相同,记录 e 用于覆盖
4putTreeVal()桶为红黑树,按树结构插入
5链表遍历遍历到尾部插入,或找到相同 key
6treeifyBin()链表长度 ≥ 8 且 table ≥ 64 时树化;否则仅扩容
7e.value = value覆盖已存在 key 的 value,返回旧值
8++size > threshold超过负载因子阈值则 resize() 扩容

六、get():查找流程

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab;
    Node<K,V> first, e;
    int n;
    K k;
    // 步骤1:table 非空且桶非空
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 步骤2:桶首节点即为目标
        if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            // 步骤3:红黑树查找
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 步骤4:链表遍历
            do {
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

步骤说明

步骤逻辑说明
1tab[(n-1) & hash]计算桶下标,取桶首节点
2first.hash == hash && key.equals(k)桶首即为目标,直接返回
3getTreeNode()桶为红黑树,O(log n) 查找
4do-while 遍历链表线性查找

七、resize():扩容流程

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    // 步骤1:计算新容量和阈值
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1;  // 双倍扩容,阈值也双倍
    }
    else if (oldThr > 0)
        newCap = oldThr;
    else {
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0)
        newThr = (int)(newCap * loadFactor);
    threshold = newThr;
    // 步骤2:创建新数组
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    // 步骤3:迁移数据
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;  // 单节点直接放
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);  // 树分裂
                else {
                    // 链表:按 (hash & oldCap) 分为低位链和高位链
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    do {
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null) loHead = e;
                            else loTail.next = e;
                            loTail = e;
                        } else {
                            if (hiTail == null) hiHead = e;
                            else hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = e.next) != null);
                    if (loTail != null) { loTail.next = null; newTab[j] = loHead; }
                    if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; }
                }
            }
        }
    }
    return newTab;
}

扩容要点

项目说明
新容量newCap = oldCap << 1,容量翻倍
单节点迁移newTab[e.hash & (newCap - 1)] = e,重新计算下标
链表迁移hash & oldCap 判断:0→留在原下标 j,非 0→迁到 j+oldCap
原理容量翻倍后,多出一位参与取模,该位为 0 的留在原桶,为 1 的迁到新桶,无需重新 hash 整个链表

八、Node 与 TreeNode

// 链表节点
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
    // ...
}

// 红黑树节点(继承 LinkedHashMap.Entry,间接继承 Node)
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent, left, right;
    TreeNode<K,V> prev;  // 保持链表顺序,便于退化为链表
    boolean red;
    // ...
}

九、整体执行流程

put 流程

put(key, value)
    │
    ├─ table 为空 ──→ resize() 初始化
    │
    ├─ 计算 index = (n-1) & hash(key)
    │
    ├─ 桶为空 ──→ 直接放入 newNode
    │
    └─ 桶非空
            │
            ├─ 桶首 key 相同 ──→ 覆盖 value,返回旧值
            │
            ├─ 桶为 TreeNode ──→ putTreeVal() 树插入
            │
            └─ 桶为链表
                    │
                    ├─ 遍历找到相同 key ──→ 覆盖 value
                    │
                    └─ 遍历到尾部 ──→ 尾插 newNode
                            │
                            └─ 链表长度 ≥ 8table64 ──→ treeifyBin() 树化
    │
    └─ ++size > threshold ──→ resize() 扩容

get 流程

get(key)
    │
    ├─ table 为空或桶为空 ──→ return null
    │
    ├─ index = (n-1) & hash(key)
    │
    ├─ 桶首 key 匹配 ──→ return first.value
    │
    └─ 桶有后继节点
            │
            ├─ 桶为 TreeNode ──→ getTreeNode() 树查找
            │
            └─ 桶为链表 ──→ 遍历 next 直到 key 匹配或 null

resize 流程

resize()
    │
    ├─ 计算 newCap(默认 oldCap << 1)
    │
    ├─ 创建 newTab[newCap]
    │
    └─ 遍历 oldTab
            │
            ├─ 桶为空 ──→ 跳过
            │
            ├─ 单节点 ──→ newTab[hash & (newCap-1)] = e
            │
            ├─ TreeNode ──→ split() 树分裂迁移
            │
            └─ 链表 ──→ 按 (hash & oldCap) 拆成 lo/hi 两条链
                    │
                    ├─ lo 链 ──→ newTab[j]
                    └─ hi 链 ──→ newTab[j + oldCap]

十、关键设计总结

设计点作用
hash 扰动高 16 位与低 16 位异或,减少低位碰撞
2 的幂容量(n-1) & hash 替代取模,位运算更快
负载因子 0.75在空间与碰撞之间折中,过高碰撞多,过低浪费空间
链表 + 红黑树链表短时 O(1) 插入,长时 O(log n) 查找,避免退化
扩容时拆链hash & oldCap 判断迁移位置,无需重新 hash

十一、常见问题

Q:为什么容量是 2 的幂?
A:(n-1) & hash 等价于 hash % n,位运算比取模快;且扩容时可用 hash & oldCap 快速判断新下标。

Q:为什么负载因子是 0.75?
A:泊松分布统计结果,0.75 时碰撞与空间利用较均衡。

Q:链表何时转红黑树?
A:链表长度 ≥ 8 且 table 长度 ≥ 64;否则先扩容,可能缓解碰撞。

Q:红黑树何时退化为链表?
A:树节点数 ≤ 6 时(UNTREEIFY_THRESHOLD),在 resize 或 remove 时退化。