HashMap源码解析

578 阅读9分钟

带着问题看HashMap源码(基于JDK8)

  • HashMap由于涉及到多个数据结构,所以变成了面试题的常客,下面带着以下几个面试常见问题去阅读JDK8中HashMap的源码
    1. HashMap底层数据结构
    2. HashMap的put过程
    3. HashMap的get过程
    4. HashMap如何扩容,扩容为啥是之前的2倍
    5. HashMap在JDK8中为啥要改成尾插法

1、HashMap底层数据结构

  • HashMap的数据结构是数组 + 链表 + 红黑树
    • 默认是存储的Node节点的数组
    Node<K,V>[] table;
    
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash; // 存储的key的hash值
        final K key;    // key键
        V value;        // value值
        Node<K,V> next; // 链表指向的下一个节点
    
    • 当Node节点中链表(next)长度超过8时会将链表转换为红黑树TreeNode(Node的子类)以提高查询效率
    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;
    
  • Node[]数组的初始长度默认为16,并且必须为2^n的形式(具体原因下面会有解释)
    /**
     * The default initial capacity - MUST be a power of two.
     * 默认初始容量为16,并且必须为2的幂数
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    
  • HashMap默认的阈值threshold = 负载因子loadFactor(默认为0.75)*容量capacity,即初始时默认为16 * 0.75 = 12
    • 表示当hashMap中存储的元素超过该阈值时,为了减少hash碰撞,会对hashMap的容量Capacity进行resize扩容,每次扩容都是之前的2倍,扩容后会重新计算hash值即重新计算在新的存放位置并插入
    /**
     * The load factor used when none specified in constructor.
     * 当没有在构造中指定loadFactor加载因子时,默认值为0.75
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
  • HashMap中链表转换成红黑树的条件
    // 当链表节点数量大于8时转换为红黑树
    static final int TREEIFY_THRESHOLD = 8;
    // 当红黑树节点数量小于6时转换为链表
    static final int UNTREEIFY_THRESHOLD = 6;
    // 链表转换为红黑树前提是整个map节点总数至少大于64,如果总数小于64采用的方案是扩容
    static final int MIN_TREEIFY_CAPACITY = 64;
    
    注意:链表转换为红黑树的条件是:map节点总数>64 且 要转换的链表长度>8

2、HashMap的put过程

put & putIfAbsent

/**
 * Associates the specified value with the specified key in this map.
 * If the map previously contained a mapping for the key, the old
 * value is replaced.
 * 将指定的值与此映射中的指定键相关联。如果映射以前包含键的映射,则旧的值被替换
 *
 * @param key key with which the specified value is to be associated    key值
 * @param value value to be associated with the specified key           key对应的Value值
 * @return the previous value associated with key, or null if there was no mapping for key
 * 当hashmap中已有当前key覆盖更新并返回旧的Value,如果没有返回null
 */
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
// onlyIfAbsent参数为true,表示仅在不包含该key时会插入,已包含要插入的key时则不会覆盖更新
@Override
public V putIfAbsent(K key, V value) {
    return putVal(hash(key), key, value, true, true);
}

hash方法计算key的hash值

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

putVal相关代码

/**
 * Implements Map.put and related methods
 *
 * @param hash hash for key                                 key的hash值,通过hash方法获取
 * @param key the key                                        键
 * @param value the value to put                             值
 * @param onlyIfAbsent if true, don't change existing value  当已有key时是否覆盖更新
 * @param evict if false, the table is in creation mode.      
 * @return previous value, or null if none           返回旧的值,如果没有相同的key返回null 
 */
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、第一次put时table为null,就会触发resize,将初始化工作延迟到第一次添加元素时,懒加载
    if ((tab = table) == null || (n = tab.length) == 0)  
        n = (tab = resize()).length;
    // 2、将hash值与capacity-1进行&运算(相当于hash%size)得出数组存放的位置;
    // 当此位置上还未存放Node时,直接初始化创建一个Node(hash,key,value,null)并放置在该位置
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;e
        // 3、假如该位置已经有值,但存储的key完全相同时,直接将原来的值赋值给临时e
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
    // 4、假如该位置有值,key值也不同,先判断该Node是不是一个TreeNode类型(红黑树,Node的子类)
    //    就调用putTreeVal方法执行红黑树的插入操作
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
     // 5、假如该位置有值,key值也不同,Node也不是一个TreeNode红黑树类型,
     //    便会对链表进行遍历并对链表长度进行计数,遍历到链表中有相同key的节点会跳出遍历
     //    当链表长度计数的值超过8(包含数组本身上的Node)时
     //    就会触发treeifyBin操作即将链表转化为红黑树
            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;
            }
        }
        // 这里主要针对相同的key做处理,当onlyIfAbsent为true时就不覆盖,为false时覆盖更新
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    // 6、当hashMap存储的元素数量超过阈值就会触发resize扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

resize扩容相关代码

/**
 * Initializes or doubles table size.  If null, allocates in
 * accord with initial capacity target held in field threshold.
 * Otherwise, because we are using power-of-two expansion, the
 * elements from each bin must either stay at same index, or move
 * with a power of two offset in the new table.
 *
 * @return the table
 */
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
    }
    // 这里针对构造器中自行设置了initialCapacity的情况
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    // 针对第一次put时,Node数组相关参数初始化
    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;
    // 扩容时将旧的Node移到新的数组操作
    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)
                    // 这个方法中可能会涉及到树转化为链表,条件是当树的元素个数 < 6
                    ((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;
                        // 判断高位是1还是0
                        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;
}

put大致的流程总结

  1. 第一次put元素时会触发resize方法,其实是将hashMap的Node[]数组初始化工作进行了类似懒加载的处理
  2. 将hash值与capacity-1进行&运算(其实就相当于hash%capacity,只是&运算效率更高)计算出当前key要放置在数组中的位置;当该位置无值时就会直接初始化创建一个Node(hash,key,value,null)并放置在该位置,如果已有值就先判断存储和插入的key是否相等,相等的话通过onlyIfAbsent参数判定是否要覆盖更新并返回旧值
  3. 如果已有值并且与要存储的key不等,就先判定该Node是否是一个TreeNode(红黑树,Node的子类),是的话就调用putTreeVal方法执行红黑树的插入操作
  4. 如果已有值并且与要存储的key不等也不是一个红黑树节点TreeNode就会对Node链表进行遍历操作,遍历到链表中有相同key就跳出根据onlyIfAbsent参数判定是否要覆盖更新,如果没有便新建Node,放置在Node链表的Next位置;如果链表长度超过8时便会将链表转化为红黑树并重新插入
  5. 最后判断HashMap存储的元素是否超过了阈值,超过阈值便会执行resize扩容操作,并且每次扩容都是之前的2倍。扩容后重新进行hash&(capacity-1)计算元素的插入位置重新插入 image.png

3、HashMap的get过程

get方法执行

  • 实质上是调用的getNode方法
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

getNode方法

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 先判断Node数组是否为空或length为0或是否存储的值本身为null,如果是直接返回null
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 当匹配到节点数组上的Node的hash和key都相同时直接返回该Node
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
        // 判断Node.next,如果为TreeNode红黑树类型就利用getTreeNode方法进行红黑树的查找
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
            // 不是红黑树结构就是链表结构,进行链表遍历操作,直至找到链表中hash和key值都相等
            // 的元素便返回该Node
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

get大致的流程总结

  1. get方法实质调用的是getNode方法
  2. 首先通过hash(key)方法计算出key的hash值,再通过hash&(capacity-1)计算(相当于hash%capacity,只是&运算效率更高)出要查找的Node数组中的元素位置
  3. 假如Node数组为null或者数组length为0或者该位置本身存储的元素就是null就直接返回null
  4. 假如该位置存储的元素不为null,直接对该位置的Node的hash和key进行匹配,假如都相等便匹配成功返回该Node
  5. 假如该数组上的Node不匹配就获取该Node的next元素,首先判断该元素是否是一个TreeNode红黑树节点类型的Node,如果是就利用getTreeNode方法进行红黑树的查找,找到返回该节点,找不到返回null
  6. 如果next节点的Node不是TreeNode表明是一个链表结构,直接循环遍历该链表,直至找到该值,或最后一个链表元素仍然不匹配就跳出循环返回null

4、HashMap如何扩容,扩容为啥是之前的2倍

  • HashMap中当存储的元素数量超过阈值时就会触发扩容,每次扩容后容量会变成之前的2倍
  • 因为扩容为2倍时,capacity-1转换成2进制后每一位都为1,使得hash&(capacity-1)计算(相当于hash%capacity,只是&运算效率更高)得出要存放的新位置要么是之前的位置要么是之前的位置+之前的capacity,使得在扩容时,不需要重新计算元素的hash了,只需要判断最高位是1还是0就好了(hash&oldCapacity),一方面降低了hash冲突,一方面提升了扩容后重新插入的效率 image.png

5、HashMap在JDK8中为啥要改成尾插法

  • 参考:https://juejin.cn/post/6844903682664824845
  • HashMap在jdk1.7中采用头插入法,在扩容时会改变链表中元素原本的顺序,以至于在并发场景下导致链表成环的问题。而在jdk1.8中采用尾插入法,在扩容时会保持链表元素原本的顺序,就不会出现链表成环的问题了