HashMap源码解析

393 阅读5分钟

JDK1.8 HashMap源码解析,单纯为个人理解记载,仅供参考,如有理解歧义或错误,欢迎指出讨论。(有时间会不断完善的,争取把所有方法都罗列出来)

2021-07-25

  1. 添加《底层数据结构简述》
  2. 添加《获取逻辑简述》

底层数据结构简述

/* 部分代码省略 */
class Node<K,V> {
    final int hash;
    final K key;
    V value;
    Node next;
}
transient Node<K,V>[] table;
class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {}
class LinkedHashMap.Entry<K,V> extends HashMap.Node<K,V> {}

HashMap底层采用Node[]进行存储,以key的hash值作为索引定位数据,一个Node储存同一hash值的所有数据。当key的hash碰撞次数(也就是Node自身长度)达到一定阈值TREEIFY_THRESHOLD,并且当前Node[]长度小于MIN_TREEIFY_CAPACITY,则对Node[]进行resize()操作。如果当前Node[]长度大于MIN_TREEIFY_CAPACITY,则将当前hash值索引定位到的Node转换成TreeNode进行存储。
PS:TREEIFY_THRESHOLD为静态常量,值为8。
PS:MIN_TREEIFY_CAPACITY为静态常量,值为64。
PS:TreeNode是一个红黑树结构

获取逻辑简述

根据key的hash值定位需要获取的数据的索引位置。对该节点Node进行遍历,比较传入的key与Node中的key,找到key相等的节点,返回该节点的value

threshold 扩容阈值,当实例化时如果指定了容器的大小,会对该值进行赋值,如果实例化时容器大小为0,则该值为1,如果>0则该值通过以下代码进行计算得出。

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

我们在new一个HashMap实例时,可以给定两个值分别是int类型的initialCapacity和float类型的loadFactorinitialCapacity为HashMap的容积,默认为1 << 4 = 16loadFactor为HashMap在判断扩容时的计算因子,默认为0.75f,扩容阈值默认为loadFactor * initialCapacity = (1 << 4) * 0.75f 。在实例化时initialCapacity可以为0,loadFactor不能为0

public V put(K key, V value) 源码解析

/**
 * 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
 * @param value value to be associated with the specified key
 * @return the previous value associated with <tt>key</tt>, or
 *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 *         (A <tt>null</tt> return can also indicate that the map
 *         previously associated <tt>null</tt> with <tt>key</tt>.)
 */
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) 源码解析

put(K key, V value)调用

/**
 * Implements Map.put and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
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)
        /* 
         * 判断当前HashMap是否有值,如果没有值,进行初始化容积
         * table为实际的数据结构,真实存储的数据
         * resize()对当前table进行初始化或者扩容
         * table的size始终时2的幂
         */
        //当前容积
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        /* 
         * 根据位运算,计算出key应该保存的index位置,如果该位置没有值,则创建一个新节点并且进行赋值
         * 最大的index与key的散列值进行位运算,计算出key对应的index值
         */
        tab[i] = newNode(hash, key, value, null);
    else {
        /*
         * 根据key计算出的数组index处已经存在值了,
         * 一种是key值完全相同
         * 一种是key值的hash相同,实际内容不同
         */
        /*
         * TreeNode extends LinkedHashMap.Entry extends HashMap.Node
         */
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            /*
             * 第一种情况,散列出的hash相同,并且key的实际值也相同
             */
            e = p;
        else if (p instanceof TreeNode)
            /*
             * 如果数组对象获取到的是TreeNode,通过TreeNode方法获取value
             */
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                /*
                 * 递归处理赋值操作
                 */
                if ((e = p.next) == null) {
                    /*
                     * 如果hash值相同,实际值不同,并且下一节点值为空,则直接赋值给下一节点
                     */
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        /*递归的深度达到了预定阈值TREEIFY_THRESHOLD8的时候,转换成树进行存储*/
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    /*如果下一节点的hash值相等,并且key实际值相等,则跳出循环*/
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            /*
             * 最终计算出key值已存在,判断是否使用新value将旧value进行覆盖,并返回旧值
             */
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            /*
             * LinkedHashMap支持方法,LinkedHashMap中会对该方法进行实现
             */
            afterNodeAccess(e);
            return oldValue;
        }
    }
    //被修改的次数加一
    ++modCount;
    /* 
     * threshold下一次扩容的大小
     * 当前容积如果大于下次扩容阈值,则进行扩容
     */
    if (++size > threshold)
        resize();
    //LinkedHashMap支持方法,LinkedHashMap中会对该方法进行实现
    afterNodeInsertion(evict);
    return null;
}

final void treeifyBin(Node<K,V>[] tab, int hash) 源码解析

这是一个树化的方法,很多地方都有用到。

/**
 * Replaces all linked nodes in bin at index for given hash unless
 * table is too small, in which case resizes instead.
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        /*
         * MIN_TREEIFY_CAPACITY 树化的阈值
         * 如果小于阈值,进行resize()
         * 只有当数组长度超过阈值才进行树化操作
         */
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        /*
         * 将key以下的所有next对象转换成树,并进行前后节点转换关联
         */
        /*
         * 第一次循环时,hd为空,tl为空,hd=p=e,tl=p=e,后续递归中hd时不变的,也就是说hd是Tree的根节点
         */
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        if ((tab[index] = hd) != null)
            /* 
             * 如果key的插入位置是有值的,继续进行下面这个不知道是什么的操作。
             */
            hd.treeify(tab);
    }
}

final void treeify(Node<K,V>[] tab) 难道这才是真正树化的过程吗,有点晕

/**
 * Forms tree of the nodes linked from this node.
 */
final void treeify(Node<K,V>[] tab) {
    TreeNode<K,V> root = null;
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        x.left = x.right = null;
        if (root == null) {
            x.parent = null;
            x.red = false;
            root = x;
        }
        else {
            K k = x.key;
            int h = x.hash;
            Class<?> kc = null;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph;
                K pk = p.key;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
                    dir = tieBreakOrder(k, pk);

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    x.parent = xp;
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    root = balanceInsertion(root, x);
                    break;
                }
            }
        }
    }
    moveRootToFront(tab, root);
}

final Node<K,V>[] 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)
                /*
                 * 在这里进行了扩容阈值调整,调正大小为2倍
                 */
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            /*
             * 这里进行了容积初始化,初始容积为 1 << 4 = 16
             */
            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) {
                /*
                 * 这里看着像是递归值copy
                 */
                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;
    }