如果该内容未能解决您的问题,您可以点击反馈按钮或发送邮件联系人工。或添加QQ群:1381223

HashMap底层实现原理和源码分析:揭秘Java集合框架的核心

HashMap底层实现原理和源码分析:揭秘Java集合框架的核心

HashMap 是 Java 集合框架中最常用的数据结构之一,它以其高效的查找、插入和删除操作而著称。本文将深入探讨 HashMap 的底层实现原理,并结合源码进行详细分析。

HashMap 的基本结构

HashMap 基于哈希表(Hash Table)实现,哈希表是一种数据结构,它通过哈希函数将键(key)映射到数组中的一个位置(索引),从而实现快速访问。HashMap 的核心结构包括:

  1. 数组(Node<K,V>[] table):用于存储键值对的桶(bucket)。
  2. 链表(Node<K,V>):当哈希冲突发生时,相同索引的键值对会形成一个链表。
  3. 红黑树(TreeNode<K,V>):当链表长度超过一定阈值(默认是8)时,链表会转换为红黑树以提高查找效率。

哈希函数和索引计算

HashMap 使用 hash() 方法计算键的哈希值,然后通过 (n - 1) & hash 计算索引,其中 n 是数组的长度。这样的计算方式可以确保索引在数组范围内,并且尽可能均匀分布。

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

插入操作

当插入一个新的键值对时,HashMap 会:

  1. 计算哈希值:使用 hash() 方法计算键的哈希值。
  2. 确定索引:通过 (n - 1) & hash 计算索引。
  3. 处理冲突
    • 如果索引位置为空,直接插入。
    • 如果已有元素,判断是否为同一个键,如果是则更新值。
    • 如果不是同一个键,检查是否需要转换为红黑树,然后将新键值对插入链表或红黑树中。
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;
        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;
                }
                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);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

扩容机制

HashMap 的容量达到阈值(threshold)时,会触发扩容操作。扩容过程包括:

  1. 创建一个新的更大的数组
  2. 重新计算每个元素的哈希值,并将它们插入到新的数组中。
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;
                        }
                        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;
}

应用场景

HashMap 广泛应用于以下场景:

  • 缓存系统:由于其快速查找特性,常用于实现缓存。
  • 数据统计:用于统计数据的频率或出现次数。
  • 配置管理:存储配置信息,方便快速访问。
  • 数据库索引:作为数据库索引的一部分,提高查询效率。

通过对 HashMap 的底层实现原理和源码分析,我们可以更好地理解其性能特点和使用场景,从而在实际开发中更有效地利用这一强大的数据结构。