HashMap原理刨析(自用)

HashMap源码解析(JDK8)

散列表

HashMap是根据散列表来设计的

散列表,也叫做哈希表,它是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度,也是一种典型的“空间换时间”的做法。hash的基本概念就是将任意长度的输入,通过hash算法映射成固定长度的输出,但是这种行为可能会产生两个相同的hash值,也就是可能会发生哈希冲突。

当你向4个桶存放5个数据时,必然会有一个桶的数据个数大于1,所以哈希冲突是没有办法避免的。

HashMap采用的是“拉链法”来解决哈希冲突,HashMap在每次存放数据时会用寻址算法,找到要存放的位置,如果这个位置已经被占用,会将要存放数据的key与这个位置数据的key进行比较,一样就替换,不一样则以链表的形式放在数据的下一个节点的位置上,当然HashMap源码不止判断了这些。

HashMap存储数据的数据结构

HashMap的数据结构是由数组+链表+红黑树组成的,内部有一个Node类,每个数据单元都会用Node进行包装,其中包含key,value,next和hash字段。

产生哈希冲突会产生链表,当链表长度大于8并且容量大于64时HashMap会将链表优化为红黑树,小于6时会再次变为链表。

优化成红黑树主要时为了减小时间复杂度

当HashMap中没有发生哈希冲突时,其时间复杂度为O(1)(数组嘛),发生哈希冲突后产生的链表时间复杂度为O(n),如果链表过长会极大的减少查询效率,所以需要优化为红黑树(O(logn))来降低时间复杂度。
那为什么要选红黑树不用avl树呢?
红黑树相比avl树,在检索的时候效率其实差不多,都是通过平衡来二分查找。但对于插入删除等操作效率提高很多。红黑树不像avl树一样追求绝对的平衡,他允许局部很少的不完全平衡,这样对于效率影响不大,但省去了很多没有必要的调平衡操作,avl树调平衡有时候代价较大,所以效率不如红黑树。

HashMap的实例化

HashMap的几个接下来要说到的属性字段

具体有什么用接下来一点一点说

常量:

默认初始容量

    /**
     * The default initial capacity - MUST be a power of two.
     */
    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.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

负载因子

    /**
     * The load factor used when none specified in constructor.
     */
    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.
     */
    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;

树化的最小数组长度

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

变量:

存放数据的数组

    /**
     * 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.)
     */
    transient Node<K,V>[] table;

扩容的最大容量

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @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;

HashMap的三个构造函数

其实应该算两个,因为有一个是另外一个的重载,这里忽略无参构造的解释,里面就一行代码。

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

参数说明:

initialCapacity代表初始容量

loadFactor代表负载因子

主要说一下public HashMap(int initialCapacity, float loadFactor)这个方法。

首先在构造方法中需要判断initialCapacity,小于0抛出异常,大于最大容量则将最大容量赋值给它。

接下来判断负载因子,小于零或不是一个数字Float.isNaN(loadFactor)都会抛出异常。

接着会调用tableSizeFor(initialCapacity)方法来计算最大扩容容量threshold

table主要用于调整数组的大小,因为HashMap的数组大小都是2的倍数,所以如果输入的是3,那么数组容量就要变成4,11就要变成16,有兴趣可以研究下tableSizeFor方法的计算过程,那么为什么要赋值给threshold(总所周知threshold = (capacity * load factor),源码的注释中有写到),这就要说一下HashMap的扩容方法了。

HashMap真正初始化数组是在第一次put的时候,这时会调用扩容方法来对你输入的初始容量进行调整,也会对threshold重新进行计算。

接下来来刨析一下HashMap的put方法

HashMap的put方法

put方法根据哈希冲突的情况大致分为四种情况

  • 要存放的位置没数据(没有哈希冲突)

  • 要存放数据的位置已经有一个数据,并且key相同,替换(没有哈希冲突)

  • 要存放数据的位置存在数据并且key不相等(要处理哈希冲突)

  • 要存放数据的位置存在红黑树(哈希冲突严重)

    /**
     * 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值,其目的是为了让高位也参与寻址运算
        // 寻址函数为(n - 1) & hash,n为数组长度,hash为key的hashCode
        // 如果n为16,则 n - 1 的二进制为 1111,与hash值进行与运算只有低4位参与运算,0010 1010和0100 1010的运算结果都是一样的
        // 扰动函数的目的就是将其高16位与低16位进行混合得出新的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 如果为true,则不要更改现有值。
     * @param evict 如果为false,则表处于创建模式。
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {

        // tab:数组,p:节点指针,n:数组长度,i:计算得出的数组下标
        Node<K,V>[] tab; Node<K,V> p; int n, i;

        // 前面提到过,如果数组没有初始化或数组长度为0,则需要进行扩容操作,第一次put完成table初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        // (n - 1) & hash为寻址算法,得出数组下标
        // 第一种情况,该位置没有数据,则直接存放
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        // 如果有值则继续判断
        else {
            // 都是一些临时变量
            Node<K,V> e; K k;
            
            // 第二种情况:如果已经存在并且与其key相同,替换,具体的替换操作在下面进行
            // 判断:p的hash是否与传入的hash相同(p在上一个if被赋值),hash相同只能表明扰动后的hash值相同,需要进一步判断key是否相同
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            
            // 对应上面的第四中情况:已经树化,则用putTreeVal(红黑树的插入操作,不做解释,详情请了解下数据结构与算法的红黑树)进行处理,没有相同的key的数据则返回null
            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);
                        // 如果链表长度大于等于8则进行树化
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            // 里面还会再判断数组长度是否大于64,如果小于则只进行扩容不进行树化操作
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 如果找到相同的key则直接跳出循环,e在上一个if判断已经被赋值
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 如果e不为空,则说明只需要替换值,不用做插入操作,modCount不会增加
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 如果数据个数大于threshold,则需要进行扩容
        if (++size > threshold)
            resize();
        // 空方法,这个是为LinkedHashMap服务的方法,LinkedHashMap会对它进行实现
        afterNodeInsertion(evict);
        return null;
    }

接下来是HashMap的扩容方法

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.
     *
     * @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;

        // 已经过次扩容的情况,下面的HashMap的常量和变量都说明过
        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
        }

        // 调用带参构造会走这里,将旧的threshold赋值给新容量,下面会对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);
        }

        // 对应使用带参构造实例化对象的情况,对threshold重新进行计算
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        // 将newThr赋值给threshold
        threshold = newThr;

        // 上面都是准备操作,接下来才是真正的扩容!
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 果如oldTab为空则直接返回newTab,不为空则进行扩容
        // 扩容不逐行说明
        // 大概就是将旧表数组每个下标的出的链表拆分为高低链
        // 假如原数组的容量为8,所以参与寻址运算的只有低4位(寻址算法:(n - 1) & hash)
        // 扩容后变为16,参与寻址运算的位低5位,比原来多一位
        // 按照多的那一位将一条链表拆分为高低链,高链为1,低链为0
        // 为0的链表在原来的位置不变(101 = 0101,所以不变),高链的下标变为原来的下标加8
        // 树的话与链表相同,因为树的节点类是继承Node,红黑树在做修改操作时内部也会维护着一条链表
        // 拆分后如果节点数小于等于6会变为链表
        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;
    }

接下来解析一下remove方法,虽然不常用,但是就怕面试问到

HashMap的remove方法

    /**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @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 remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    /**
     * Implements Map.remove and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue 如果为true,则仅在值相等时删除
     * @param movable 如果为false,则在删除时不要移动其他节点
     * @return the node, or null if none
     */
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        // n为数组长度, p为节点指针
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        // 如果table初始化完毕并且寻址成功(找到的下标处存在值),开始执行删除操作
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {

            // e和上面的p用于遍历链表,node为找到相同值后用于存储的临时变量
            Node<K,V> node = null, e; K k; V v;
            
            // 如果p的key为要删除的值,则直接将p存入node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;

            // 如果p的下一个节点为空,则未查找到要删除的值,删除失败,若不为空则遍历查找
            else if ((e = p.next) != null) {

                // 如果树化,则调用getTreeNode来获得目标节点
                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);
                }
            }

            // 判断node是否为空,不为空则找到需要删除的对象,进行删除操作
            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;
                // 也是个空方法,为LinkedHashMap提供服务
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

最后是常用的get方法

HashMap的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;
        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;

        // 如果该下标处有数据则进行查找操作,没有则返回null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {

            // 还是一如既往的判断下第一个节点,如果key相同直接返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 如果第一个节点的下一个节点不为空则继续进行查找
            if ((e = first.next) != null) {
                // 判断是否树化,树化则调用红黑树的getTreeNode方法,直接返回查找到的数据
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                
                // 进行链表的遍历,找目标数据则返回,找不到结束遍历,返回null
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

其实还有个replace方法也挺常用

HashMap的replace方法

@Override
    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

应该不用说明了,直接调用的get方法。

参考文献:https://www.bilibili.com/video/av80572671?from=search&seid=16183031872432969592&spm_id_from=333.337.0.0

posted @ 2020-07-30 20:48  快点ヤ给我起来♪♫  阅读(124)  评论(1)    收藏  举报