美文网首页
靠别人不如靠自己(1)——HashMap源码总结

靠别人不如靠自己(1)——HashMap源码总结

作者: 墨_0b54 | 来源:发表于2021-10-11 21:10 被阅读0次

    1. HashMap

    1.1. 概述

    HashMap类的定义如下:

    public class HashMap<K,V> extends AbstractMap<K,V> 
                             implements Map<K,V>, Cloneable, Serializable 
    

    特点

    • 线程不安全
    • 可被克隆(浅克隆),可被序列化
    • 允许使用null键和null值
    • 由数组+链表+红黑树实现(JDK8以前由数组+链表实现,即链地址法)
    • 判断两个 key 相等的标准是:hashCode 值相等,两个 key 通过 equals() 方法返回 true
    • 判断两个 value相等的标准是:两个 value 通过 equals() 方法返回 true

    1.2. 常量 & 属性 & 构造方法

        // 链表 -> 树 的条件之一,节点数 > 8
        static final int TREEIFY_THRESHOLD = 8;
        // 树 -> 链表 的条件之一,节点数 < 6
        static final int UNTREEIFY_THRESHOLD = 6;
        // 链表 -> 树 的条件之一,table容量至少64
        static final int MIN_TREEIFY_CAPACITY = 64;
        // 桶初始容量
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
        // 桶最大可扩容容量,因为int最大值为2^31 -1,每次扩容是容量翻倍,会溢出。
        static final int MAXIMUM_CAPACITY = 1 << 30;
        // 默认负载因子
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    
        // 桶
        transient Node<K,V>[] table;
        // 键值对数量,transient表示该字段不会被序列化
        transient int size;
        // 桶被修改的次数,用于快速失败机制
        transient int modCount;
        // 下一次扩容的大小
        int threshold;
        // 负载因子,只有这个属性可被用户在构造map时赋值,或默认0.75
        final float loadFactor;
    
        // 默认的构造函数
        public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; }
        // 指定容量大小,
        public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); }
        // 指定容量大小和负载因子大小
        public HashMap(int initialCapacity, float loadFactor) {
            // 指定的容量大小不可以小于0,否则将抛出IllegalArgumentException异常
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
             // 判定指定的容量大小是否大于HashMap的容量极限
            if (initialCapacity > MAXIMUM_CAPACITY)
                initialCapacity = MAXIMUM_CAPACITY;
             // 指定的负载因子不可以小于0或为Null,若判定成立则抛出IllegalArgumentException异常
            if (loadFactor <= 0 || Float.isNaN(loadFactor))
                throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
            this.loadFactor = loadFactor;
            // 计算下一次扩容的大小,tableSizeFor方法非常巧妙的将初始容量计算为2的幂次
            this.threshold = tableSizeFor(initialCapacity);
        }
        //传入一个Map集合,将Map集合中元素Map.Entry全部添加进HashMap实例中
        public HashMap(Map<? extends K, ? extends V> m) {
            this.loadFactor = DEFAULT_LOAD_FACTOR;
            //此构造方法主要实现了Map.putAll()
            putMapEntries(m, false);
        }
    

    1.3. 核心方法的实现

    1.3.1. put 的实现

     public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
     //HashMap.put的具体实现,如果值已存在,替换为新值并返回旧值
     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;
            if ((p = tab[i = (n - 1) & hash]) == null) //(n - 1) & hash 取余(巧妙的位运算)
                tab[i] = newNode(hash, key, value, null); // 桶的第一个节点
            else { 
                Node<K,V> e; K k;
                if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) // key相等判断(下面会多次出现)
                    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) { // 此时binCount = 链长度 - 1
                            p.next = newNode(hash, key, value, null);
                            if (binCount >= TREEIFY_THRESHOLD - 1) // 原链长度 >= 8,转换为树
                                treeifyBin(tab, hash);
                            break;
                        }
                        if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) // key相等判断
                            break;
                        p = e;
                    }
                }
                if (e != null) { //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;
        }
    

    整个put发生了什么?

    1. 判断是否初始化桶
    2. 对hash与桶容量取余,确定元素在桶中的下标
    3. 如果下标处没有节点,直接new一个Node并插入
    4. 否则判断当前桶保存的是链表还是树,然后执行对应的插入动作
    5. 如果当前节点属于TreeNode,调用TreeNodeputTreeVal方法,进行树的插入逻辑
    6. 如果当前节点不属于TreeNode,在链表中查找key,如果没有找到key,new一个Node置于链表尾部
    7. 如果加入新节点后链表长度大于8,则调用树化函数treeifyBin,将链表转换为树
    8. 最后判断桶是否需要resize
    9. 有一个问题,先树化再resize,那resize可能又会使树退化
    • 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;
            }
    }
    // LinkedHashMap内的键值对
    static class LinkedHashMap.Entry<K,V> extends HashMap.Node<K,V> {
            Entry<K,V> before, after;
            Entry(int hash, K key, V value, Node<K,V> next) {
                super(hash, key, value, next);
            }
    }
    // 继承自Node,TreeNode同时拥有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;
            TreeNode(int hash, K key, V val, Node<K,V> next) {
                super(hash, key, val, next);
            }
    }
    
    • 三者都实现了Map的Entry(键值对)接口
    • TreeNode继承了Node,所以TreeNode实际上保留了链,这里基本上已经解答了map的遍历
    • treeifyBin方法解析
    // 将链表转换为树
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //树化的必要条件,桶长度至少达到 MIN_TREEIFY_CAPACITY = 64,否则resize
        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); //Node转为TreeNode
                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); //链表转为红黑树的方法,都是指针操作,忽略
        }
    }
    // 保留Node的属性数据,所以链表转为树的时候依旧还是链表,所以树转为链表的时候叫`退化`
    TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
            return new TreeNode<>(p.hash, p.key, p.value, next);
    }
    

    treeifyBin主要判断是否需要将链转为红黑树,如果需要就把Node转为TreeNode,然后使用treeify方法树化链表

    • resize方法解析
    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) { // 达到最大容量(2^30)不能扩容
                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;
        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
        table = newTab;
        if (oldTab != null) { //如果不是初始化table,将节点移到新table
            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 { 
                                //如果hash & oldCap不等于0,则节点需要移动到新索引位置桶
                                //[hash & (newCap - 1)] == [hash & (oldCap - 1) + oldCap] >= oldCap
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //需要移动oldCap位置
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
    

    整个resize发生了什么?

    1. 计算桶扩容后的容量,根据扩容后的容量计算下一次扩容的阈值,最大容量为2^30,每次扩容都是翻倍
    2. 申请新的桶,将原桶中的数据迁移到新的桶
    3. 原有桶中的数据重新计算索引,重新计算后只有两种情况,维持原索引或者移动到(原索引大小+原容量大小)的位置
    4. 如果原桶的节点是树,执行树移动的split方法
    • split方法解析
    final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
        TreeNode<K,V> b = this;
        // Relink into lo and hi lists, preserving order
        TreeNode<K,V> loHead = null, loTail = null; // 从这里开始
        TreeNode<K,V> hiHead = null, hiTail = null;
        int lc = 0, hc = 0;
        for (TreeNode<K,V> e = b, next; e != null; e = next) {
            next = (TreeNode<K,V>)e.next;
            e.next = null;
            if ((e.hash & bit) == 0) {
                if ((e.prev = loTail) == null)
                    loHead = e;
                else
                    loTail.next = e;
                loTail = e;
                ++lc;
            }
            else {
                if ((e.prev = hiTail) == null)
                    hiHead = e;
                else
                    hiTail.next = e;
                hiTail = e;
                ++hc;
            }
        } //一直到这里,节点移动逻辑与resize方法一样
        if (loHead != null) { 
            if (lc <= UNTREEIFY_THRESHOLD) //如果树大小<=6,树退化为链
                tab[index] = loHead.untreeify(map);
            else {
                tab[index] = loHead;
                if (hiHead != null) // (else is already treeified)
                    loHead.treeify(tab); //整理树,都是指针操作,忽略
            }
        }
        if (hiHead != null) { 
            if (hc <= UNTREEIFY_THRESHOLD) //如果树大小<=6,树退化为链
                tab[index + bit] = hiHead.untreeify(map);
            else {
                tab[index + bit] = hiHead;
                if (loHead != null)
                    hiHead.treeify(tab);
            }
        }
    }
    
    • split方法首先用与resize一样的方法移动节点,最后再判断是否需要退化树,如果不需要,重新将链整理为树
    • 树的退化只有两处,一处是这里resize(在加入新元素后,达到扩容的阈值后调用),另一处就是在remove,并不根据UNTREEIFY_THRESHOLD常量进行判断,但是基本上能达到元素数量达到2-6个时退化

    1.3.2. get 的实现

    //get方法实际上调用了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) {
            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 {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null); //链遍历
            }
        }
        return null;
    }
    

    get方法没什么好说的,根据Node类型进行遍历查找

    1.3.3. remove 的实现

    //remove方式实际调用了removeNode方法
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) { //查找remove的节点
                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);
                }
            }
            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;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }
    final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
                                      boolean movable) {
        // ...忽略
        // 个人认为比较关键的,判断是否应该将树退化
        // 并没有要求树节点数量一定小于7,但是基本上在树节点数量为2-6时会退化
        if (root == null || root.right == null ||
                    (rl = root.left) == null || rl.left == null) {
                    tab[index] = first.untreeify(map);  // too small
                    return;
        }
        //...忽略
    }
    

    remove比较关键的是,树会退化为链,但并不是树节点数量小于7就会立刻退化
    在removeTreeNode方法上有这么一句注释:The test triggers somewhere between 2 and 6 nodes, depending on tree structure
    大致意思是:测试在 2 到 6 个节点之间触发,具体取决于树结构

    1.3.4. keySet & values & entrySet 的实现

    public Set<K> keySet() {
            Set<K> ks;
            return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
    }
    public Collection<V> values() {
        Collection<V> vs;
        return (vs = values) == null ? (values = new Values()) : vs;
    }
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }
    

    可以看到上面三个方法实际上都是返回了集合对象,这里我们只关注遍历方式的实现,即迭代器iterator的实现。
    三个集合的iterator实现实际上都是来自于HashIterator,是一样的

    • HashIterator 的实现
    abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // 用于快速失败
        int index;             // current slot
        HashIterator() {
            expectedModCount = modCount; //初始化当前修改次数
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // 找到第一个有节点的索引,初始化next
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }
        public final boolean hasNext() {
            return next != null;
        }
        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount) // 如果遍历中使用其他方式修改了map,则直接失败
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) { //刷新next和current指针
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }
        public final void remove() { //执行删除方法,并刷新expectedModCount
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }
    
    • 从迭代器的实现可以发现,遍历实际上还是使用链,这就是为什么TreeNode继承了Node
    • 没有看源码以前,以为对树的遍历是使用树的迭代器,但是现在细想一下,单独实现树的遍历会非常麻烦,这样牺牲了一些指针占用的空间,但是提供了更多的便利
    • 再想想网络上那么多文章,只说了HashMap在JDK1.7到JDK1.8的变化只是增加了红黑树,但是只字未提遍历方式的变化,那么JDK1.8以前是怎么遍历的呢?那时候肯定是没有树的

    1.4. 其他问题

    • JDK8之前,多线程环境下的扩容问题,采用头插法会导致死循环,头插法会将链表翻转一遍,在多个线程同时扩容时,两个线程各自翻转一次就有可能造成循环链表问题

    • 为什么不直接用hashCode方法得到的结果计算索引?

    static final int hash(Object key) {
        int h;
        //计算 key.hashCode() 并将hash的较高位(异或)传播到较低位
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    

    官方解释是,由于table使用二次幂掩码,因此位变化仅在当前掩码上的hash集合将始终发生冲突。
    掩码是一串二进制代码对目标字段进行位与运算,屏蔽当前的输入位。(回忆一下子网掩码)
    因此key.hashCode() ^ (h >>> 16),将高位异或传递到低位,可以降低冲突
    在JDK1.8以前采用扰动方法,进行了更多次数的位运算,运算次数更多,效率也更低

    相关文章

      网友评论

          本文标题:靠别人不如靠自己(1)——HashMap源码总结

          本文链接:https://www.haomeiwen.com/subject/azgholtx.html