Java-HashMap源码解析(一)

Java-HashMap源码解析(一)

基本介绍

HashMap为Java的基本集合类,由于有着优秀的查找能力(时间复杂度为O(1)),在平时的工作与面试中也是常客。在平时的使用当中,同学们只需要掌握get,put方法,即可熟练操作。但如果想要真正的了解它,离不开其优秀的结构设计,以及扩展性。通过这篇文章,主要从源码的角度对HashMap进行剖析,让你认识不一样的HashMap。

基本属性

	//默认初始化容器数量 16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

     //最大容器数量	巧妙的使用了 位运算
    static final int MAXIMUM_CAPACITY = 1 << 30;
    
    //默认加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //判断Node结构是用列表 还是用 红黑树 如果链表长度增长后大于8 
    //则触发treeifying转换为 红黑树
    static final int TREEIFY_THRESHOLD = 8;
    //如果红黑树长度缩减后小于6,则将Node结构调整为链表结构 
    static final int UNTREEIFY_THRESHOLD = 6;
	//触发红黑树第二种情况: 容器数量>64;
    static final int MIN_TREEIFY_CAPACITY = 64;

在这里需要向大家解释一下,其中几个重要属性的含义。
1.在数组中我们往往用new int[10] 来初始化一个容量为10的数组,即该数组中总共可装入10个数据。与此不同,HashMap中 capacity的含义实际为分桶的数量,而不是实际可装入的数据的最大值。在HashMap中巧妙的使用了很多位运算,也是提升HashMap的亮点,在后文中会详细介绍几个关于位运算的巧妙之处。

HashMap使用到的数据结构

HashMap优秀的数据结构是降低其时间复杂度的关键,尤其是在JDK1.8版本以后,对其数据结构做了优化,使得其性能达到最优。

Node[] Node数组

无论是在JDK1.8前后,HashMap所依赖的外层查找数据结构均为数组。原因很简单,数组可以达到其时间复杂度为O(1)的标准。可以根据传入参数的Key,在计算其Hash值之后,直接准确获取到数据所在的数组位置。

Node 节点

在这里有一些区别了。从数组中找到对应index,就可以找到具体的Value了吗?不尽然。比如:h1=1, h2=11,capacity=10,那么就会出现Hash冲突问题,即两个元素虽然不同,但通过hash散列再取余之后,所得到的值相同,从而占据了数组中的同一个位置,如果仅存一个就会造成数据的丢失。
在大学的数据结构中,面对Hash冲突问题有几种解决方式,如果遗忘的话,可以回顾一下
其中HashMap所采用的解决Hash冲突的方式为:链地址法。
在JDK1.8之前,Node的实现为链表的方法。

链表
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        ...

这样的结构,无疑是一个单向链表,思考一下会有什么样的问题呢?链表的查找的时间会随着链表的增长而不断变大。当链表过长时,会影响到其整体HashMap的查找速率。
所以在JDK1.8,Node结构的实现做了一定调整。
在这里插入图片描述

红黑树

在1.8之后,JDK引入了红黑树结构对HashMap的链表结构进行了优化。利用红黑树查找时间复杂度为O(logn)的优势,避免当链表在过长情况下造成的性能降低的情况。
Q:单纯用红黑树替换链表可以吗?
A:可以,但是不好,由于红黑树只是在链表过长时,提高了其查询效率。当链表很短的情况下,链表与红黑树的查找效率是相差无几的,但红黑树的结构较链表复杂,反而增大了消耗,所以应该结合两者来处理。
JDK1.8版本,哈希表结构
红黑树的数据结构实现:

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

在这里插入图片描述

依赖关系图
从依赖关系图可以看出,无论我们使用哪中具体的数据结构,使用Node进行声明即可,完美的结合了链表和 红黑树两种数据结构。那么如何进行转换的呢?又是何时触发转换呢?

HashMap的部分代码

resize()

作用用于初始化;或者扩容,其实际操作是将现有数组 复制计算 赋入 新的数组中并返回。 当前操作比较重,且当HashMap的capacity发生变化时就会被处触发

    /**
     * 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
     * 初始化或者扩充双倍 hashMap的大小;如果为空,则用默认值创建;
     * 否则,创建一个 capacity是当前2倍的 HashMap 并返回;
     */
    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;
            }		//容量扩大2两倍;
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //如果自定义设置 容量 且小于16 则保持不变
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults	//为指定容量 和 加载因子 均赋值为默认值 
        	//threshold= 加载因子* 容量大小 即触发条件
            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"})
    /**从以上操作我们知道, 初始化HashMap时, 
    *  如果构造函数没有指定initialCapacity, 则table大小为16
    *  如果构造函数指定了initialCapacity, 则table大小为threshold,
    *  即大于指定initialCapacity的最小的2的整数次幂
    
    *  从下面开始, 初始化table或者扩容, 实际上都是通过新建一个table来完成
    */ 
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        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;
                        //旧数组该位Node 为红黑树
                    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;
    }

treeifyBin 链表转 红黑树

此处用到了MIN_TREEIFY_CAPACITY
当前 capacity没有达到MIN_TREEIFY_CAPACITY=64时,则优先扩容;
否则进行链表的遍历 将其封装为 红黑树,替换之前的链表。

    /**
     * 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)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            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)
                hd.treeify(tab);
        }
    }

put底层代码

此处用到了TREEIFY_THRESHOLD=8;
每当put一个元素,都应该考虑 1.未发生冲突则直接插入;
2.当存在相同key则替换。
2.发生冲突: 1)插入后链表长度>8则尝试转为二叉树;
2)插入后链表长度<=8 则插入;


    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)
        	//如果当前table为空,会重新创建HashMap 中的数组
            n = (tab = resize()).length;
            //如果插入点 并不存在hash冲突 直接插入一个Node节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //p为数组中现有数据 如果当前hash与 p的hash相同,且key相同。
            //则进行值的覆盖
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = 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;
                    }
                    //如果链表中某个节点的key与 当前key相同,则将其value替代
                    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;
                    //此处为空,用于其子类的调用扩充 如LinkedHashMap
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //如果大小
        if (++size > threshold)
            resize();
             //此处为空,用于其子类的调用扩充 如LinkedHashMap
        afterNodeInsertion(evict);
        return null;
    }

get代码

    public V get(Object key) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) == null)
            return null;
        if (accessOrder)
            afterNodeAccess(e);
        return 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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
            //如果是红黑树 则转为红黑树
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                    //否则 遍历整个list 查找。
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

梳理一下HashMap 中 使用 链表 到使用 红黑树的逻辑:
当某链表长度增大至 TREEIFY_THRESHOLD=8时,

  1. 如果capaticy<MIN_TREEIFY_CAPACITY=64
    进行扩容capaticy<<1,并且重新计算每个容器中的链表,以减少链表的长度;
  2. 如果capaticy>=MIN_TREEIFY_CAPACITY
    将该链表中的每个节点逐个加入红黑树中。

HashMap细节

为什么HashMap的capacity总为2^N?

在HashMap中,大量使用了位运算与‘与’运算,其最重要的在计算hash取余时,其源码如下:

//取余数
tab[(n - 1) & hash]
//扩容
newCap = oldCap << 1

由于2^N的二进制为1111111,而对于 与运算而言 ,任何数与1=1,起到了取余数的作用。

为什么HashMap的loadfactor总为0.75?

源码介绍:

  * Because TreeNodes are about twice the size of regular nodes, we
     * use them only when bins contain enough nodes to warrant use
     * (see TREEIFY_THRESHOLD). And when they become too small (due to
     * removal or resizing) they are converted back to plain bins.  In
     * usages with well-distributed user hashCodes, tree bins are
     * rarely used.  Ideally, under random hashCodes, the frequency of
     * nodes in bins follows a Poisson distribution
     * (http://en.wikipedia.org/wiki/Poisson_distribution【**泊松分布**) with a
     * parameter of about 0.5 on average for the default resizing
     * threshold of 0.75, although with a large variance because of
     * resizing granularity. Ignoring variance, the expected
     * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
     * factorial(k)). The first values are:
     *
     * 0:    0.60653066
     * 1:    0.30326533
     * 2:    0.07581633
     * 3:    0.01263606
     * 4:    0.00157952
     * 5:    0.00015795
     * 6:    0.00001316
     * 7:    0.00000094
     * 8:    0.00000006
     * more: less than 1 in ten million

简单翻译一下就是在理想情况下,使用随机哈希码,节点出现的频率在hash桶中遵循泊松分布,同时给出了桶中元素个数和概率的对照表。
从上面的表中可以看到当桶中元素到达8个的时候,概率已经变得非常小,也就是说用0.75作为加载因子,每个碰撞位置的链表长度超过8个是几乎不可能的。

为什么HashMap的MAXIMUM_CAPACITY = 1 << 30?

由于HashMap的Capacity使用的是Int类型,而int类型为32为,其中最高位为符号为,所以最多可达到1<<30次方,其最高位0表示正。

结语

以上是自己总结的一些相关HashMap的东西,知其然,还要知其所以然,才能不断进步。在之后还会更新关于HashMap,CurrentHashMap,HashTable,LinkedHashMap的区别等。以及一些促进学习的数据结构,从HashMap的源码中不难看出,好的的数据结构对程序的优化能力起到重要作用。善于从代码中找到数据结构的实现,提升自己。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值