MK
摩柯社区 - 一个极简的技术知识社区
AI 面试

Java HashMap的底层实现原理剖析

2021-02-052.7k 阅读

1. 概述

在Java编程中,HashMap是一个常用的数据结构,它实现了Map接口,允许我们存储键值对(key - value pairs),并提供了快速的查找、插入和删除操作。HashMap之所以高效,是因为它基于哈希表(hash table)的实现。哈希表是一种数据结构,它使用哈希函数(hash function)将键映射到一个特定的位置,从而能够快速定位到对应的值。

2. 基本结构

HashMap的底层主要由一个数组(Node[] table)构成,数组中的每个元素被称为桶(bucket)。每个桶实际上是一个链表(在Java 8及之后,链表长度超过一定阈值会转化为红黑树)的头节点。当我们向HashMap中插入一个键值对时,会根据键的哈希值计算出应该存储在数组中的哪个位置(桶)。如果该位置已经有元素(发生哈希冲突),则会以链表或红黑树的形式将新元素添加到该位置。

下面是HashMap的简化代码结构:

public class HashMap<K, V> {
    transient Node<K, V>[] table;

    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 K getKey()        { return key; }
        public V getValue()      { return value; }
        public V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
    }
}

3. 哈希函数

哈希函数在HashMap中起着关键作用,它决定了键值对在数组中的存储位置。在HashMap中,哈希函数的实现如下:

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

这里首先获取键的hashCode值,然后通过(h = key.hashCode()) ^ (h >>> 16)进行位运算。^是异或运算符,h >>> 16表示将h无符号右移16位。这种操作主要是为了让高位和低位都能参与到哈希值的计算中,从而减少哈希冲突的可能性。

4. 容量与负载因子

  • 容量(Capacity)HashMap中数组的大小,默认初始容量为16。容量必须是2的幂次方,这样可以利用位运算快速定位桶的位置。例如,当容量为16时(二进制表示为10000),通过(n - 1) & hashn为容量,hash为键的哈希值)就可以快速计算出应该存储在哪个桶中。
  • 负载因子(Load Factor):负载因子是衡量HashMap满的程度的一个指标,默认值为0.75。它的作用是当HashMap中的元素数量达到capacity * loadFactor时,就会进行扩容操作。例如,当容量为16,负载因子为0.75时,当元素数量达到16 * 0.75 = 12时,就会触发扩容。

5. 插入操作(put方法)

当调用put(K key, V value)方法向HashMap中插入一个键值对时,会执行以下步骤:

  1. 计算键的哈希值:通过hash(key)方法计算键的哈希值。
  2. 确定桶的位置:使用(n - 1) & hashn为当前数组容量)来确定键值对应该存储在数组的哪个桶中。
  3. 检查桶是否为空:如果桶为空,则直接在该位置创建一个新的Node节点。
  4. 处理哈希冲突:如果桶不为空,说明发生了哈希冲突。在Java 8之前,会将新元素以链表的形式插入到桶的头部;在Java 8及之后,当链表长度小于8时,以链表形式插入到尾部,当链表长度大于等于8且数组容量大于等于64时,链表会转化为红黑树,以提高查找效率。
  5. 更新值:如果键已经存在,则更新对应的值。
  6. 检查是否需要扩容:插入完成后,检查当前元素数量是否达到capacity * loadFactor,如果达到则进行扩容。

以下是简化的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;
        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;
}

6. 扩容操作(resize方法)

扩容是HashMap中的一个重要操作,当元素数量达到capacity * loadFactor时,会触发扩容。扩容时,会创建一个新的数组,其容量是原来的两倍,并将原数组中的所有元素重新计算哈希值并插入到新数组中。

以下是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;
                        }
                        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;
}

在扩容过程中,会重新计算每个元素在新数组中的位置。由于新数组容量是原来的两倍,所以原数组中每个桶的元素会被分配到新数组的两个桶中(通过e.hash & oldCap判断),这种方式可以减少重新计算哈希值的开销。

7. 查找操作(get方法)

当调用get(Object key)方法从HashMap中获取值时,会执行以下步骤:

  1. 计算键的哈希值:通过hash(key)方法计算键的哈希值。
  2. 确定桶的位置:使用(n - 1) & hashn为当前数组容量)来确定键值对应该存储在数组的哪个桶中。
  3. 查找元素:如果桶为空,则直接返回null;如果桶不为空,则在链表或红黑树中查找与键匹配的元素。如果找到了匹配的元素,则返回对应的值;否则返回null

以下是简化的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 &&
            ((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;
}

8. 删除操作(remove方法)

当调用remove(Object key)方法从HashMap中删除一个键值对时,会执行以下步骤:

  1. 计算键的哈希值:通过hash(key)方法计算键的哈希值。
  2. 确定桶的位置:使用(n - 1) & hashn为当前数组容量)来确定键值对应该存储在数组的哪个桶中。
  3. 查找并删除元素:如果桶为空,则直接返回null;如果桶不为空,则在链表或红黑树中查找与键匹配的元素。如果找到了匹配的元素,则将其从链表或红黑树中删除,并返回对应的值;否则返回null

以下是简化的remove方法实现:

public V remove(Object key) {
    Node<K, V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null?
        null : e.value;
}

final Node<K, V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K, V>[] tab; Node<K, V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K, V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K, V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K, V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

9. 遍历操作

HashMap支持多种遍历方式,常见的有以下几种:

  • 遍历键(keySet)
HashMap<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);

for (String key : map.keySet()) {
    System.out.println(key);
}
  • 遍历值(values)
for (Integer value : map.values()) {
    System.out.println(value);
}
  • 遍历键值对(entrySet)
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

10. 线程安全性

HashMap是非线程安全的。如果在多线程环境下使用HashMap,可能会导致数据不一致或其他问题。例如,在扩容过程中,如果多个线程同时操作,可能会导致链表形成环,从而在遍历链表时出现死循环。

如果需要在多线程环境下使用类似HashMap的功能,可以考虑使用ConcurrentHashMapConcurrentHashMap通过分段锁等机制,提供了线程安全的哈希表实现,允许多个线程同时对不同的段进行操作,从而提高并发性能。

通过对HashMap底层实现原理的剖析,我们了解了它的基本结构、哈希函数、插入、查找、删除等操作的实现细节,以及扩容、遍历和线程安全性等方面的知识。这有助于我们在实际编程中更加合理地使用HashMap,提高程序的性能和稳定性。