关于面试:HashMap源码阅读

2次阅读

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

本文基于 JDK1.8  > 读完本文预计须要 25 分钟 (因有大量源代码,电脑屏观看体验较佳)

摘要

HashMap 置信这是呈现频率最高的面试点之一,应该是面试问到烂的面试题之一,同时也是 Java 中用于解决键值对最罕用的数据类型。那么咱们就针对 JDK8 的 HashMap 独特学习一下!

次要办法

要害变量:

    /**
     * The default initial capacity - MUST be a power of two.
     * 初始容量大小 必须是 2 的次幂
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     * 最大的容量大小
     * 超过这个值就将 threshold 批改为 Integer.MAX_VALUE,数组不进行扩容
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * 负载因子 为什么是 0.75?因为统计学中 hash 抵触合乎泊松散布,7- 8 之间抵触最小
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 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.
     * 链表大于这个值就会树化
     * 留神:树化并不是整个 map 链表,而是某一个大于此阈值的链表
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     * 小于这个值就会反树化
     */
    static final int UNTREEIFY_THRESHOLD = 6;

四个构造方法:

// 构造方法 1
// 指定初始容量大小,负载因子
public HashMap(int initialCapacity, float loadFactor) {if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity:" +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY) //1<<30 最大容量是 Integer.MAX_VALUE;
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor:" +
                                               loadFactor);
        this.loadFactor = loadFactor;
        //tableSizeFor 这个办法用于找到大于等于 initialCapacity 的最小的 2 的幂
        this.threshold = tableSizeFor(initialCapacity);
    }

// 构造方法 2
// 其实调用了上边的构造方法 1 负载因子给的默认值 0.75
public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

// 构造方法 3
// 空参结构,均应用默认值
public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}
    
// 构造方法 4
// 与其余三个相比,初始化了
public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;//0.75f
        // 调用了 putVal 办法,而 putVal 办法中有 resize 办法,有初始化
        putMapEntries(m, false);
    }

对四个构造方法简略总结一下:

1、前三个构造函数并没有初始化,都是用到的时候去初始化

2、构造方法 4 相当于用到了 put 办法,所以初始化了

hashmap->hash()

/**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     * 计算 key.hashCode()并将哈希的较高位(XOR)扩大为较低。* 因为该表应用 2 的幂次掩码,因而仅在以后掩码上方的位中发生变化的哈希集将始终发生冲突。*(家喻户晓的示例是在小表中蕴含间断整数的 Float 键集。)因而,咱们利用了一种变换,* 将向下扩大较高位的影响。在速度,实用性和位扩大品质之间须要衡量。* 因为许多常见的哈希集曾经正当散布(因而无奈从扩大中受害),* 并且因为咱们应用树来解决容器中的大量抵触,因而咱们仅以最便宜的形式对一些移位后的位进行 XOR,* 以缩小零碎损失,以及合并最高位的影响,否则因为表范畴的限度,这些位将永远不会在索引计算中应用。*/
    static final int hash(Object key) {
        int h;
        // 为什么 ^ (h >>> 16) 更加散列, 性能考量,不便位运算
        // 不便在 put,get 办法中 (n - 1) & hash 计算数组下标
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        //HashMap 中 key 值能够为 null, 看到 0 那么咱们能够判断 null 值肯定存储在数组的第一个地位
    }

hashmap->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.
         * // 将指定的值与此映射中的指定键关联。如果该映射先前蕴含了该键的映射,则旧值将被替换。*
         * @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) {
            // 把 key 先去 hash 一下拿到 hash 值
            return putVal(hash(key), key, value, false, true);
        }
    
        /**
         * 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 //if true 则不扭转原来存在的值
         * @param evict if false, the table is in creation mode.//if false 则表处于创立模式
         * @return previous value, or null if none
         */
        final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                       boolean evict) {// 数组 + 链表 + 红黑树,链表型(Node 泛型) 数组,每一个元素代表一条链表,则每个元素称为桶
            //HashMap 的每一个元素,都是链表的一个节点(Entry<K,V>)这里也就是 Node<K,V>
    
            //tab: 桶 p: 桶 n: 哈希表数组大小 i: 数组下标 (桶的地位)
            Node<K,V>[] tab; Node<K,V> p; int n, i;
            //1. 判断以后桶是否为空,空的就调用 resize() 办法(resize 中会判断是否进行初始化)if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            //2. 判断是否有 hash 抵触,依据入参 key 与 key 的 hash 值找到具体的桶并判空,空则无抵触 间接新建桶
            //?为什么采纳 (n - 1) & hash 计算数组下标,感兴趣的能够深刻理解
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            //3. 以下示意有抵触,解决 hash 抵触
            else {
                Node<K,V> e; K k;// 均为长期变量
                //4. 判断以后桶的 key 是否与入参 key 统一,统一则存在,把以后桶 p 赋值给 e, 笼罩原 value 在步骤 10 进行
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                //5. 如果以后的桶为红黑树,用 putTreeVal() 办法写入 赋值给 e
                else if (p instanceof TreeNode)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                //6. 则以后的桶是链表 遍历链表
                else {for (int binCount = 0; ; ++binCount) {if ((e = p.next) == null) {
                            //7. 尾插法,链表下一个节点是 null(链表开端),就 new 一个新节点写入到以后链表节点的前面
                            p.next = newNode(hash, key, value, null);
                            //8. 判断是否大于阈值,须要链表转红黑树
                            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                //binCount 从 0 开始的, 所以当 binCount 为 7 时,链表长度为 8(算上数组槽位开始的那个节点,总长度为 9),则须要树化桶
                                treeifyBin(tab, hash);
                            break;
                        }
                        //9. 与步骤 4 统一,如果链表中 key 存在则间接跳出 步骤 10 笼罩原值
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;
                    }
                }
                //10. 存在雷同的 key 的 Node 节点, 则笼罩原 value
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    //onlyIfAbsent 为 true:不扭转原来的值;false:扭转原来的值
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    //LinkedHashMap 用到的回调办法
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
             /* 记录批改次数标识
             用于 fast-fail,因为 HashMap 非线程平安,在对 HashMap 进行迭代时,如果期间其余线程的参加导致 HashMap 的构造发生变化了(比方 put,remove 等操作),须要抛出异样 ConcurrentModificationException
             */
            ++modCount;
            //11. 容量超过阈值,扩容
            if (++size > threshold)
                resize();
            //LinkedHashMap 用到的回调办法
            afterNodeInsertion(evict);
            return null;
        }

那么咱们来总结一下 put 办法:

1、开始,入参 key、value
2、判断以后 table 是否为空或者 length=0?是,去扩容,(resize() 办法中有判断是否初始化)否,依据 key 算出 hash 值并失去插入的数组的索引
        判断找到的这个 table[i] 是否为空?是,直接插入,再到步骤
            否,判断 key 是否存在?是,间接笼罩对应的 value, 再到步骤 3
                否,去判断以后这个 table[i] 是不是 treeNode?是,应用红黑树的形式插入 key、value
                    否,开始遍历链表筹备插入
                        判断链表长度是不是大于 8?是,链表转红黑树插入 key、value
                            否,以链表的形式插入 key、value 如果 key 存在就间接笼罩对应 value

3、判断 map 的 size() 是否大于阈值?是 就去扩容 resize()
4、完结 

hashmap->get()


public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * 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;
        //1、判断以后数组不为空并长度大于 0 && 由 key 的 hash 值找到对应数组下的桶(可能是红黑树或者链表)if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //2、先判断桶的第一个节点 如果 key 统一 返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //3、再判空下一个节点不为空 && 判断是红黑树还算链表
            if ((e = first.next) != null) {
                //4、如果是红黑树 则按红黑树形式取值
                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;
    }

那么咱们来总结一下 get() 办法:

1、开始,入参 key
2、判断以后的数组长度不为空 &&length>0
    是 return null;
    否,去判断第一个节点,如果 key 合乎,返回
        再去判断下一个节点是否为空
            是,return null
            否,判断否是红黑树?是,按红黑树的形式取值
                否,遍历链表取值

3、完结 

hashmap->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.
     * 初始化或减少表大小。如果为空,则依据字段阈值中放弃的初始容量指标进行调配。* 否则,因为咱们应用的是 2 的幂,所以每个 bin 中的元素必须放弃雷同的索引,或者在新表中以 2 的幂偏移。* @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;
        //1、原数组扩容
        if (oldCap > 0) {
            // 如果原数组长度大于最大容量,把阈值调最大,return
            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;
        // 应用空参结构,用默认值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;//16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//0.75*16=12
        }
        // 应用了指定 initialCapacity 的构造方法,新阈值为 0,则计算新的阈值
        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"})
        //2、用新的数组容量大小初始化数组
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        // 如果仅仅是初始化过程, 到此结束 return newTab
        table = newTab;
        //3、开始扩容的次要工作,数据迁徙
        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;
                            // 这是一个外围的判断条件,感兴趣的能够深刻理解?为什么这么做
                            //= 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);
                        // 把整个低位链表放到新数组的 j 地位
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // 把整个高位链表放到新数组的 j +oldCap 地位上
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

总结一下 resize() 办法:

1、开始,拿到原数组
2、对原数组扩容
      2.1 如果原数组中的容量到最大,不再扩容,return 原数组
      2.2 把原数组容量大小与阈值都扩充一倍
3、如初始化用的指定 initialCapacity 的构造方法,则用原阈值作为新容量
4、如初始化时候用的空参结构,用默认容量与默认阈值
5、如初始化用的指定 initialCapacity 的构造方法,阈值 =0,计算新的阈值
6、用新的容量初始化数组,如果是初始化,完结返回新数组
7、开始扩容,做数据迁徙
      7.1 遍历原数组 copy 数据到新数组
            7.1.1 如数组中只有一个元素,则间接复制
            7.1.2 如元素是红黑树数类型,则按红黑树的形式解决
            7.1.3 对原数组的链表进行解决
                      定义一个高位链表、一个低位链表(对原链表拆分)开启一个循环,遍历原链表
                            判断条件 e.hash & oldCap == 0?
                                  是,把这些链表节点放到低位链表
                                  否,放到高位链表
                      循环完结,遍历链表实现
                      把整个低位链表放到新数组 j 地位
                      把整个高位链表放到新数组 j +oldCap 地位
      7.2 循环完结,遍历旧数组实现
8、返回新数组 

我想这会浏览完结之后应该对 HashMap 有了肯定的意识,心愿能在面试或者工作中帮到您!

Hongchen 闲聊

看起来是不是有点酷,它的名字叫”茑屋“,北京温榆河公园。

上周跟女友在家待闷了出门转转,于是咱们找了个公园,秋冬的公园还是比拟萧瑟。

年底了,疫情零零散散,心愿早点过来!peaceeeee

感激浏览

满腹经纶,如有你发现有谬误的中央,能够在后盾或者评论提出来,我会加以批改。
感谢您的浏览,欢送并感激关注!

正文完
 0