关于java:HashMap-源码逐行分析j-oldCap-桶位置重分配公式手写验证

4次阅读

共计 11068 个字符,预计需要花费 28 分钟才能阅读完成。

阐明

本文基于 jdk 8 编写。

HashMap 的构造

  1. 图中的数组是 table 属性,hashMap 根底的属性。一个数组,用于承载 node,table 的每一个格被称为桶。
  2. node 是 hashMap 中根底的 node 节点,用于存储 key, value。
  3. 桶地位计算的公式是 (n - 1) & hash,n 指 table 的长度,hash 指 key 的 hash 值。
  4. 桶地位计算时有可能呈现 hash 抵触的景象,在 jdk 1.7 及之前采纳的是把 node 拼接成链表的形式。但如果 hash 抵触重大,桶地位上的链表会很长,影响查问性能。从 jdk 1.8 开始,改成了链表 + 红黑树的形式,在一个桶地位上元素很多的状况下,树的查问效率优于链表。

要害属性

table

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     *
     * hashMap 根底的属性。一个数组,用于承载 node,table 的每一个格被称为桶
     */
    transient Node<K,V>[] table;

Node

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     *
     * hashMap 中根底的 node 节点,用于存储 key, value
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
    }

modCount

这个属性与了解 HashMap 的外围流程无关,如果读者只关怀外围流程,能够不必关注。

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     *
     * 用于记录批改次数,每次增删改时会保护它的值
     * 在一个迭代器开始的时候,会把 modCount 用一个局部变量 mc 记录下来。迭代器遍历实现后,如果发现 modCount 和 mc 不雷同,阐明迭代期间 hashMap 进行过批改,则抛出异样。* 对于迭代器遍历,能够看一下 EntrySet 外部类的 forEach 办法
     */
    transient int modCount;

对于迭代器遍历,能够看一下 EntrySet 外部类的 forEach 办法。

    /**
     * 请留神,源码里 EntrySet 的其余成员属性和成员办法,这里不作展现
     */
    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {public final void forEach(Consumer<? super Map.Entry<K,V>> action) {Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                // 把 modCount 用一个局部变量 mc 记录下来
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                // 迭代器遍历实现后,如果发现 modCount 和 mc 不雷同,阐明迭代期间 hashMap 进行过批改,则抛出异样。if (modCount != mc)
                    throw new ConcurrentModificationException();}
        }
    }

threshold 扩容阈值

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * 扩容阈值,由 capacity * loadFactor 失去。决定何时 hashMap 执行 resize 办法扩容
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

loadFactor 加载因子

    /**
     * The load factor for the hash table.
     *
     * 加载因子,决定了 hashMap 理论能存储的元素容量
     *
     * @serial
     */
    final float loadFactor;

    /**
     * The load factor used when none specified in constructor.
     *
     * 默认的 loadFactor 加载因子
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

加载因子是示意 HashMap 中元素的填满的水平。加载因子的目标是,为了升高 HashMap 中的 hash 抵触几率,避免大量 node 都因为 hash 抵触变成了链表或树,同时均衡占用的空间开销。

加载因子越大,填满的元素越多。长处是,空间利用率高了。毛病是,hash 抵触的机会加大了。

加载因子越小,填满的元素越少。长处是,抵触的机会减小了。毛病是,空间节约多了。

默认的加载因子 DEFAULT_LOAD_FACTOR = 0.75f 算是在 hash 抵触几率与空间开销间做了取舍均衡。

构造方法

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity. 初始容量,由 capacity * loadFactor 能够失去扩容阈值 threshold
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

咱们能够留神到,HashMap 里并没有 capacity 这个属性,咱们在构造方法中传入的 capacity,其实会通过 capacity * loadFactor 计算,失去扩容阈值 threshold。

put 办法

    /**
     * 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.
     *
     * put 办法,调用 Val 给指定的 key 增加对应的 value
     *
     * @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) {
        // 第一个 boolean false 示意:当要 put 的 key 在 hashMap 中已存在时,会间接笼罩原有 value。第二个 boolean true 不必关怀,与主流程无关。return putVal(hash(key), key, value, false, true);
    }

putVal

    /**
     * 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  如果指标 key 在 hashMap 中曾经存在,则不会笼罩原有的 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;
        // 如果 table 还没有初始化,则初始化 table
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 桶地位计算公式: (n - 1) & hash。如果定位到的桶地位为空,则把 node 插入桶地位。p 指向桶地位
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        // 桶地位不为空,阐明呈现 hash 碰撞,走 else 分支
        else {
            Node<K,V> e; K k;
            // 通过 key 的 hash 值和 equals 办法判断桶地位上的 key 是否雷同。如果雷同则用 e 指向这个节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 判断桶地位上是否是一棵树,如果是一棵树,则调用树增加元素的办法,而后用 e 指向树上的这个节点
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            // 不是树,则阐明是链表
            else {
                // 迭代链表,binCount 是链表长度计数
                for (int binCount = 0; ; ++binCount) {
                    // 用 e 指向本次迭代的以后元素。如果本次迭代,以后元素为空,即达到了链表的尾部
                    if ((e = p.next) == null) {
                        // 向链表尾部追加 node
                        p.next = newNode(hash, key, value, null);
                        // 如果链表长度达到了阈值,把链表转换成树。链表转换树的阈值无奈批改,因为是 final 润饰的。if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 通过 key 的 hash 值和 equals 办法判断本次迭代的 key 是否雷同。如果雷同则用 e 指向这个节点。而后进行迭代链表。if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 保护以后元素,筹备下一次迭代
                    p = e;
                }
            }
            // 如果 e 不为空,阐明要增加的 key 原先已存在于这个桶地位上,笼罩原有 value。这里体现了 hashMap 的 onlyIfAbsent 选项为 false 时,呈现 key 雷同时,会间接笼罩原有 value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                // onlyIfAbsent 选项为 false 时,或原有 value 为 null 时,会间接笼罩原有 value
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 这个办法不必关怀。留给 LinkedHashMap 回调用。afterNodeAccess(e);
                // 返回原有的 value
                return oldValue;
            }
        }
        // 保护批改次数计数
        ++modCount;
        // 如果达到了扩容阈值,则 resize
        if (++size > threshold)
            resize();
        // 这个办法不必关怀。留给 LinkedHashMap 回调用。afterNodeInsertion(evict);
        // 没有找到 key 对应的 value,返回 null
        return null;
    }

有一个细节,链表转换树的阈值 TREEIFY_THRESHOLD 无奈批改,因为是 final 润饰的,之前面试被问到过。


    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     *
     * 链表转换树的阈值,无奈批改,因为是 final 润饰的
     */
    static final int TREEIFY_THRESHOLD = 8;

get 办法

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        // 依据指定的 key 查找 node,返回 node 的 value
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

getNode

    /**
     * Implements Map.get and related methods.
     * 
     * 依据指定的 key,查找 node
     *
     * @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;
        // 如果 table 不为空,且依据 key 对应到的桶地位不为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 通过 key 的 hash 值和 equals 办法判断桶地位上的 key 是否雷同
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                // 和指标 key 雷同,返回以后节点
                return first;
            // 桶地位不为空,阐明可能存在 hash 碰撞,判断桶地位上的元素是否有下一个节点
            if ((e = first.next) != null) {
                // 判断桶地位上是否是一棵树,如果是一棵树,则调用树查找元素的办法
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 不是树,则阐明是链表,迭代链表
                do {
                    // 通过 key 的 hash 值和 equals 办法判断本次迭代的 key 是否雷同
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        // 和指标 key 雷同,返回以后节点
                        return e;
                } while ((e = e.next) != null);
            }
        }
        // 没有找到 key 对应的元素,返回 null
        return null;
    }

resize 办法

常见的执行 resize() 办法的两种状况

在 HashMap 的 putVal 办法中,如果 table 未初始化,则会执行 resize(),而后就初始化 table。初始化 table 由 resize 负责。

// 如果 table 还没有初始化,则初始化 table        
if ((tab = table) == null || (n = tab.length) == 0)
    n = (tab = resize()).length;

在 HashMap 的 putVal 办法中,存储的数据量大于 threshold 时,会执行 resize() 办法。

        // 如果 hashMap 中的元素数量达到了扩容阈值,则 resize
        if (++size > threshold)
            resize();

在 putVal() 办法中,size 示意以后 HashMap 的数据量,如果 size 大于 threshold, 则会执行该办法,进行扩容操作。

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.
     *
     * 初始化 hashMap 或给 hashMap 的 table 扩容两倍
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        // oldTab 指向旧 table
        Node<K,V>[] oldTab = table;
        // 旧 table 的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // oldThr 示意旧的扩容阈值 threshold。threshold = 数组长度 * 负载因子
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            // 当旧 table 的长度大于最大容量时的解决
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 如果旧的数组长度 * 2 后小于 int 的最大值,并且旧的数组长度大于 16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 扩容阈值 * 2
                newThr = oldThr << 1; // double threshold
        }
        // 如果旧的 threshold 大于 0,初始容量设置为旧的 threshold。这里在 table 初始化时会用到
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        // 扩容阈值为 0 示意应用默认值,DEFAULT_INITIAL_CAPACITY = 16,DEFAULT_LOAD_FACTOR = 0.75,因而默认的扩容阈值为 12
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 扩容阈值为 0 时的边界条件解决
        if (newThr == 0) {float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        // 将计算后得出的阈值赋值给 threshold 属性
        threshold = newThr;
        // 不必关怀这个注解。这个注解在屏蔽一些无关紧要的正告,使开发者能看到一些他们真正关怀的正告,升高开发者的心智累赘。// 创立一个新的 table,供扩容后应用
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        // 把新 table 赋值给 hashMap 的属性
        table = newTab;
        // 如果旧 table 不为空,开始扩容
        if (oldTab != null) {
            // 迭代遍历旧 table
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                // e 指向以后桶地位的元 node,以后桶地位的 node 不为空时
                if ((e = oldTab[j]) != null) {
                    // 清空旧 table 的以后桶地位
                    oldTab[j] = null;
                    if (e.next == null)
                        // 如果以后桶地位的 node 不是链表不是红黑树,则依据桶地位计算公式,重新分配 node 的桶地位
                        newTab[e.hash & (newCap - 1)] = e;
                    // 如果以后桶地位的 node 是树,则应用树的形式,把旧树上的 node,重新分配到新的树中
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    // 不是树,则是链表
                    else { // preserve order
                        // 把链表中的所有节点分成两条链表
                        // 一条链表的 node 是不须要更换 table 下标的
                        Node<K,V> loHead = null, loTail = null;
                        // 一条链表的 node 是须要更换 table 下标的
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        // 迭代遍历链表
                        do {
                            next = e.next;
                            // 如果 e.hash & oldCap 进行二进制与运算,算出的后果为 0,即阐明该 node 所对应的数组下标不须要扭转。把该 node 追加到 loHead 链表上
                            if ((e.hash & oldCap) == 0) {if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            // 否则阐明该 node 所对应的数组下标须要扭转。把该 node 追加到 hiHead 链表上
                            else {if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        // 如果不须要更换 table 下标的 node 链表 -- loTail 不为空,则把 loTail 放在以后桶地位上
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // 如果须要更换 table 下标的 node 链表 -- hiTail 不为空,则把 hiTail 放到新的桶地位上。并且计算公式是把以后 table 下标间接 + 旧 table 的长度
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        // 返回新创建的 table
        return newTab;
    }

两个个公式

(e.hash & oldCap) == 0 判断是否须要重新分配桶地位

e 是以后 node,oldCap 是旧数组的长度。这个公式算出的后果为 0,阐明该 node (即 e) 所对应的数组下标不须要扭转。后果不为 0,阐明该 node 所对应的数组下标须要扭转。

(e.hash & oldCap) == 0 为什么能判断出是否须要重新分配桶地位?

这个公式是推导进去的,推导过程是数学,咱们不须要关注。如果想理解此公式的推导请见:HashMap 扩容时的 rehash 办法中 (e.hash & oldCap) == 0 算法推导

j + oldCap 桶地位重调配公式

j 是 node 的旧桶地位,oldCap 是旧 table 的长度。即 旧桶地位 + 旧 table 的长度。失去这个公式的运算后果,是扩容后该元素的新桶地位。能够了解为是桶地位重新分配的公式。

为什么这样能失去呢?咱们来举例答复一下。

当初咱们有一个 node key 的 hash 值是 9,对应的二进制位。旧 table 的长度 oldCap 是 8,新 table 的长度 newCap 是 16。以下是手写演算验证:

为什么 HashMap 扩容是 2 倍?

通过本文桶地位重新分配的公式 j + oldCap 手写验证,咱们能够看出,当 HashMap 扩容两倍的时候,刚好能够用到 桶地位重新分配的公式 j + oldCap,放慢计算重调配后的桶地位。同时,newCap = oldCap << 1 新 table 长度 = 旧 table 长度在二进制上左移一位,这样的位运算也很高效。

其实这里扩容倍数和桶地位重调配公式的配合,能体现出作者周密的思考和深厚的数学功底。

正文完
 0