• HashMap 源码浅析


    HashMap的常量设置

    // 默认初始长度
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    //最大长度10 7374 1824
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //转变为树的阀值(当链表长度大于8 且哈希桶数组长度大于64时转换为红黑树)
    static final int TREEIFY_THRESHOLD = 8;
    //转换为链表的阀值(当树节点小于6时将转换为链表)
    static final int UNTREEIFY_THRESHOLD = 6;
    //最小树容量
    static final int MIN_TREEIFY_CAPACITY = 64;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    哈希桶

    在JDK1.7中,HashMap是以 数组 + 链表 的形式组成的(jdk1.8增加了红黑树)。其中数组中的元素我们称之为哈希桶,它的源码如下:

    /**
    * Basic hash bin node, used for most entries.  (See below for
    * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
    */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;//hash值
        final K key;//key 值
        V value; //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;
        }
    
        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }
    
        public final int hashCode() {
            // 亦或取出hashCOde
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
    
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
    
        public final boolean equals(Object o) {
            if (o == this)
                return true;
            // 当是Map类型 比较key及value值
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    我们知道红黑树的概念是在JDK1.8中添加的,之所以添加进来是因为链表一旦过长。HashMap的性能就很受影响,而之前我们介绍了红黑树的数据结构具有快速增删改查的特点,这就有效的解决了链表过长所导致的性能问题;

    什么时候转换为红黑树?

    当链表的长度大于8且容量大于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;
        // MIN_TREEIFY_CAPACITY = 64
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)// 当链表的长度小于64时扩容
            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);//转为红黑树
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    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)
            n = (tab = resize()).length;
        // 如果tab[i]为null 则插入新的节点
        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值,key都相等 则覆盖e节点
            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 {
                // 如果key不存在 也不是树节点表明为链表 则循环准备插入链表下个节点
                for (int binCount = 0; ; ++binCount) {
                    // 链表下个节点为空时
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // binCount >= 7是转为红黑树(及链表长度大于8时)
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // key值存在 并且和下个节点(e)的hash值相等 则覆盖p节点
                    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;
        // 超出最大容量扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
    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); // 转为红黑树
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    加载因子为何设定为0.75?

    出于容量和性能的平衡考虑的结果;

    • 假如加载因子设置过大,那么发生扩容的门栏就比较高,那么扩容的频率就很低,发生Hash冲突的概率就会提高。
    • 假如加载因子设定的比较小,那么扩容的频率就会变高,那么将会占用更多的空间;并且此时,数据的存储就会比较稀疏,对各种操作的性能要求比较高!

    Hash冲突了怎么查找节点?

    我们看下获取节点的源码getNode:

    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) {
    		// while循环 判断第一个元素是否是需要查询的元素
            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);
                // 如果第一节点不为树节点  则循环判断
                do {
                    // hash 值相同且key相同  则找到此节点
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    当hash冲突了即hash值相等了,还需要判断key值是否相等来确定节点元素;

    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
     */
    //我们来解读下注释的意思:表的大小可以通过初始化或者扩容时变为原有的两倍;
    //如果为空,将根据字段阀值的初始容量分配大小
    //否则 我们将采用二次扩容的方式 每个bin中的元素必须保持在同一索引中 或者在新表中以两个偏移量的幂次移动
    //有点绕,我们结合代码来理解
    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倍 且小于最大容量  且扩容前的容量大于默认容量16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold  新阀值扩大2倍
        }
        // 扩容前容量为0  阀值大于0(即当前数组没有数据)
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr; // 新扩容的容量大小 设置为扩容前阀值(就是用户自定义的阀值)
        else {               // zero initial threshold signifies using defaults
            // 如果初始化值为0 则使用默认值
            newCap = DEFAULT_INITIAL_CAPACITY; // 新扩容的容量设置为16
            // 新扩容的阀值设置为12
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 如果新扩容的阀值为0
        if (newThr == 0) {
            // 根据新扩容容量和负载算出一个当前阀值
            float ft = (float)newCap * loadFactor;
            // 如果新扩容的容量小于最大值  并且当前阀值也小于最大值  就取当前阀值  否则为最大int值
            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) {
            // 遍历
            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
                        // 以下是链表复制部分,jdk1.8重点优化部分
                        // 注:JDK1.7中rehash 旧链表迁移新链表的时候
                        // 如果在新表的数组索引位置相同,则链表元素会倒置,而jdk1.8不会
                        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;
                            //loHead为首的链表放到数组的原位置
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            // 将hiHead为首的链表放到原位置+oldCap的位置
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107

    若HashMap 创建时没有指定大小和扩容阀值,则默认为16,负载因子是0.75。那么容量默认为12,当容量大于12时则扩容为原来16的两倍即32;从源码可以看到,扩容后会进行元素的位置调整;因为jdk1.7在迁移过程中会倒置链表,即头插法有可能倒置循环引用问题(HashMap本身即是非线程安全的,所以官方jdk1.7未处理此问题);而jdk1.8使用了尾插法,解决了此问题;但在扩容的时候依然会有线程安全的问题,并且在扩容的过程中若是红黑树则会进行拆分,否则才会进行链表迁移;

    左右旋

    左右旋的本质是为了包装树的平衡,我们知道红黑树的本质是一颗平衡二叉树!

    // 左旋
    static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                          TreeNode<K,V> p) {
        TreeNode<K,V> r, pp, rl;
        // p节点不为空 右子节点r赋值的同时也判断p节点的右子节点不为空
        if (p != null && (r = p.right) != null) {
            // 左子节点 赋值为p节点的右子节点  同时和右子节r点的左子节点相等
            // 则p是父节点
            if ((rl = p.right = r.left) != null)
                rl.parent = p;
            // pp节点赋值为右子节点的父节点  且和p节点的父节点相等 并且他们的父节点都为null
            // 则当前右子节点为根节点(red=false 根节点为黑色)
            if ((pp = r.parent = p.parent) == null)
                (root = r).red = false;
            // pp节点的左子节点 为p节点
            // 则pp的左子节点为当前右子节点
            else if (pp.left == p)
                pp.left = r;
            // 否则 pp的右子节点为当前右子节点
            else
                pp.right = r;
    
            // r的左字节变为p节点
            r.left = p;
            // p的父节点变为右子节点
            p.parent = r;
        }
        return root;
    }
    
    // 右旋和左旋相反,代码略
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    关于左右旋的更形象理解可以查阅《大话数据结构》中关于红黑树的描述;

    小结:HashMap 基本数据结构是数组(EntryNode Hash桶)+链表+红黑树;当链表节点的长度大于8,且数组的长度小于64时,对数组扩容;当链表节点长度大于8,数组长度大于64时,链表转换为红黑树;扩容的过程是,数组放在原有的索引处,链表放在原有的索引加上原有的数组长度的地方;扩容后如果树节点小于6,就将树还原成链表;

  • 相关阅读:
    外星人入侵游戏-(创新版)
    容器化部署fastdfs文件存储
    A component required a bean of type ‘XXX‘ that could not be found 解决办法
    数组在TypeScript中是如何工作的
    Java Servlet JSP使用Gson 输出JSON格式数据
    ulimit命令的使用
    [Redis]Zset类型
    使用dockerfile自定义Tomcat镜像
    基于stm32的秒表计时器设计系统Proteus仿真
    【OpenVINO™】在 Windows 上使用 OpenVINO™ C# API 部署 Yolov8-obb 实现任意方向的目标检测
  • 原文地址:https://blog.csdn.net/iME_cho/article/details/125418487