可能是最详细的HashMap(Java8)实现详解-原理+源码解析

3 篇文章 0 订阅

1、预备知识

1.1 hash

hash又称散列或杂凑,一般音译为哈希,是指一种算法、函数或数据结构,可以根据key值直接映射为存储位置,为了方便理解,见下图:
hash
示例:
假如key是一个数字,hash函数为取余,存储为数组

key=100,hash为模10,经过hash后为0,即存储在数组的0号位置

key也可以是字符串等,采用合适的hash函数,即可将key值散列到存储数组中

hash冲突

从hash原理图可以看出,hash存在冲突的情况,还是根据上面的示例,假如key为10,经过hash后,得到的存储位置也是0号位置,这就是hash冲突,为了解决hash冲突,HashMap才引入了链表和红黑树的算法。

1.2 链表

链表是大学专业课数据结构里必修的课程之一,再回顾一下:
链表
链表相对数组的优势:

  • 不需要连续的存储空间
  • 插入、删除数据不需要做数据拷贝

1.3 红黑树

红黑树是一种含有红黑结点并能自平衡的二叉查找树。它必须满足下面性质:

  • 每个节点要么是黑色,要么是红色。
  • 根节点是黑色。
  • 每个叶子节点(NIL)是黑色。
  • 每个红色结点的两个子结点一定都是黑色。
  • 任意一结点到每个叶子结点的路径都包含数量相同的黑结点。
    在这里插入图片描述
    优势: 红黑树的查找复杂度是O(logN),链表查找复杂度为O(N),因此Java8采用红黑树对链表进行优化,加快查找速度

2、实现原理

2.1 存储结构

了解了hash、链表和红黑树后,我们来看HashMap在Java8中的实现方式,HashMap正是结合了数组+单向链表+红黑树来实现的,如下图:
HashMap原理图

HashMap存储是以Node为单位的,Node分为两种,链表Node和红黑树TreeNode,链表Node包含了hash值、key、value和next,next指向下一个节点,红黑树TreeNode继承自Node,新增了red、parent、left、right、prev,用来存储树结构。

当创建一个HashMap时,首先创建的是一个Node的数组。
向HashMap中插入数据,在没有hash冲突时,直接存储在数组中;当遇到hash冲突时,会先采用链表方式存储新增的Node,但当新增Node的深度大于指定阈值后,链表裂变为红黑树。

因此,一个HashMap的的存储就包含了:一个Node数组+n个Node链表+n个TreeNode树
以下是节点Node和TreeNode定义源码

//数组和链表节点定义
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }
   ……
}
//树节点定义,树节点继承了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;
    ……
}

2.2 几个默认值

/**
     * The default initial capacity - MUST be a power of two.
     */
     //默认存储容量,是2的4次方,也就是16,这个值会影响数组大小
    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.
     */
     //最大容量,是2的30次方,当resize时新的容量小于该值时,扩容2倍,否则直接扩容到Integer的最大值(2的64次方-1)
    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;

2.3 插入流程

看注释

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //n:map长度
        //p:待插入数据经hash后,对应到table数组的Node
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果不冲突,直接新建一个Node放到table数组中
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //如果冲突,放到该hash值的链表中
        else {
            Node<K,V> e; K k;
            //查找需要插入的位置
            //如果当前Node的key与待插入的key一样,则就是当前Node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果p是树节点,把新值插入到树上
            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);
                        //如果大于链表设定深度,转为树型
                        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;
                }
            }
            //
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //预留接口
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //大小超出进行resize
        if (++size > threshold)
            resize();
        //预留接口
        afterNodeInsertion(evict);
        return null;
    }

2.4 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) {
            //MAXIMUM_CAPACITY,1<<30=2的30次方=1073741824
            //如果现有长度大于最大长度,则直接扩容为Integer的最大长度,2的64次方-1
            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
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //新建HashMap
        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;
        //如果是扩容
        if (oldTab != null) {
            //遍历原HashMap,将原HashMap中的值拷贝到新HashMap中
            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;
    }

3、明白原理后分析几个问题

3.1 为什么HashMap是不安全的

根据上面原理和代码的分析,可以看出导致HashMap线程不安全主要有以下几个原因:

  • resize时需要新建数组+链表+红黑树,并将原数据复制到新树中,如果在resize的时候进行了插入操作,可能会导致数据丢失
  • 当链表长度大于阈值时,进行treeifyBin操作,treeifyBin方法中,会新创建一颗红黑树,然后将链表中的数据复制到红黑树中,也可能导致数据丢失

了解原理后,可以很轻松的通过代码来重现,启动多个线程,同时往一个HashMap中插入数据,最好统计HashMap中保存的数据数量是否与实际插入数据数量一致,还是有很大概率重现的,我测试插入100000万个数据,基本每次都会少1-2个。
源码参考

3.2 为什么HashMap要resize

这个问题应该显而易见了,如果不进行resize,链表长度或红黑树的深度会无限增长,导致查询变慢,所以为了保证查询效率,在插入时如果HashMap大小如果大于指定阈值,就会进行resize

3.3 为什么要使用链表+红黑树

解决hash冲突常用的解决方式:

  • 开放地址法,遇到冲突后继续在数组中向后查找,直到查找到空值
  • 链接地址法,将冲突值链接到数组上,HashMap就是采用的这种方法
  • 再哈希法,冲突后,采用另外的hash函数再次进行hash,直到不冲突为止

HashMap采用的是链接地址法,并在链表的数据上进行了优化,超过指定长度后,将链表转化为红黑树,为了提升查询速度,是查询时间复杂度从O(N)降低为O(logN),那为什么不全部使用红黑树呢,因为红黑树实现复杂,插入效率低于链表,而且需要更多的存储空间。
因此,HashMap在Java8中采用了链表+红黑树的方式进行实现,综合考虑了查询效率、插入效率和存储空间利用率。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值