JDK 8 HashMap 详解及详细源码展示

JDK 8 HashMap 详解

Java 8 中的 HashMap 是一个非常重要的数据结构,它在 JDK 7 的基础上进行了重大改进,特别是引入了红黑树来优化链表过长时的性能。下面我将详细解析 HashMap 的核心概念、实现原理和源码。

一、核心概念

1. 数据结构
  • 数组 + 链表 + 红黑树:当链表长度超过阈值(8)且数组长度≥64时,链表转换为红黑树;当红黑树节点数少于6时,退化为链表。
2. 关键参数
  • 初始容量:16(默认),必须是2的幂。
  • 负载因子:0.75f,当元素数量超过容量×负载因子时触发扩容。
  • 树化阈值:8,链表长度超过此值时转换为红黑树。
  • 退化阈值:6,红黑树节点数少于此值时退化为链表。
  • 最小树化容量:64,数组长度不足时即使链表长度超过8也不树化。
3. 哈希与寻址
  • 哈希函数(h = key.hashCode()) ^ (h >>> 16),高16位与低16位异或,减少哈希冲突。
  • 寻址方式(n - 1) & hash,通过位运算替代取模,效率更高(仅当n为2的幂时等价)。

二、源码解析

1. Node 节点结构
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}
2. TreeNode 红黑树节点
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
    TreeNode(int hash, K key, V val, Node<K,V> next) {
        super(hash, key, val, next);
    }

    // 红黑树操作方法(旋转、插入、删除等)
    ...
}
3. 哈希函数
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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;
    // 初始化数组或扩容
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 计算索引位置,若为空直接插入
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 节点key已存在,直接覆盖
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 当前为树节点,调用树的插入方法
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // 链表插入
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 链表长度达到树化阈值,转换为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // key已存在,直接覆盖
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 处理已存在的键
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e); // LinkedHashMap回调
            return oldValue;
        }
    }
    ++modCount;
    // 超过阈值则扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict); // LinkedHashMap回调
    return null;
}
5. 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;
    
    // 计算新容量和阈值
    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; // double threshold
    }
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    
    // 计算新阈值
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    
    // 创建新数组并迁移数据
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    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 { // preserve order
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // 原位置
                        if ((e.hash & oldCap) == 0) {
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        // 原位置+oldCap
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    
                    // 低位链表放入原位置
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    // 高位链表放入新位置
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}
6. 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;
    // 检查表和索引位置是否存在
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 第一个节点直接匹配
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        // 遍历链表或树
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

三、JDK 8 的主要改进

  1. 红黑树优化

    • 当链表长度超过8且数组长度≥64时,转换为红黑树,将查找、插入、删除的时间复杂度从O(n)优化到O(log n)。
  2. 扩容机制优化

    • 扩容时采用高低位链表拆分,避免了JDK 7中链表成环的问题,且不需要重新计算哈希值。
  3. 性能提升

    • 哈希函数优化,减少哈希冲突;红黑树结构提升了极端情况下的性能。

四、线程安全性

  • HashMap 是非线程安全的,多线程环境下可能出现数据不一致问题。
  • 替代方案:
    • ConcurrentHashMap:线程安全的哈希表,采用分段锁(JDK 7)或CAS + synchronized(JDK 8)实现。
    • Collections.synchronizedMap:通过包装器实现同步,性能较低。

五、使用建议

  1. 初始容量设置

    • 预估元素数量,避免频繁扩容。例如,预计存储100个元素,初始容量设为100/0.75 ≈ 134,取最近的2的幂(256)。
  2. 键对象要求

    • 键必须正确实现hashCode()equals()方法。
    • 不可变对象(如String、Integer)是理想的键类型。
  3. 遍历方式

    • 使用entrySet()遍历键值对,比keySet()更高效。

六、总结

JDK 8 的 HashMap 通过引入红黑树和优化扩容机制,显著提升了性能,特别是在处理大量哈希冲突时。理解其核心原理(哈希函数、寻址方式、扩容机制、红黑树转换)对于高效使用和调优至关重要。在多线程场景下,需使用ConcurrentHashMap替代。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值