Java 源码分析 -- 全面解析 HashMap

本贴最后更新于 1984 天前,其中的信息可能已经时移世易

介绍

HashMap 是基于哈希表的 Map 接口的实现,并允许使用 null 值和 null 键。HashMap 在 JDK1.8 之前使用的是哈希表 + 链表的方式存储数据。在 JDK1.8 之后,如果链表过长则将链表转成红黑树。 

源码分析

继承

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

HashMap 继承了 AbstractMap 及实现了 Map、Cloneable 和 Serializable 接口。

成员变量

private static final long serialVersionUID = 362498820763181265L;
// aka 16 默认的初始容量  1*2*2*2*2 = 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
//最大容量是2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;   
//填充因子是0.75.如果哈希表中的元素超过了加载因子与当前容量的乘积,就调用rehash方法
static final float DEFAULT_LOAD_FACTOR = 0.75f; 
//阈值,当桶上的链表数大于这个值会转成红黑树
static final int TREEIFY_THRESHOLD = 8;
//当桶中的立案表述小于这个值则红黑树转成链表
static final int UNTREEIFY_THRESHOLD = 6; 
//转成红黑树之前,判断键值对数量大于64才会转换。
static final int MIN_TREEIFY_CAPACITY = 64;
//哈希表数组,长度一直为2的幂次
transient Node<K,V>[] table;
//键值对集合
transient Set<Map.Entry<K,V>> entrySet;
//键值对的数量
transient int size;
//统计操作次数,迭代的时候判断这个值是否变化,fail-fast抛出ConcurrentModificationException
transient int modCount;
//阈值,键值对数量大于这个值将开始扩容。threshold = table.length * loadFactor
int threshold;
//这个才是填充因子,上面DEFAULT_LOAD_FACTOR是默认的
final float loadFactor;

Node 结点

    static class Node<K,V> implements Map.Entry<K,V> {
        //存的结点的hash值
        final int hash;  
        //K和V的值,这里V不用final修饰。K用final修饰,说明键只能赋值一次,不能改变,但是值可以改变
        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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int 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;
            //instanceof 判断对象o是否是类Map.Entry的一个实例
            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;
        }
    }

构造函数

    //传入初始容量和填充因子
    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;
        //计算出来threshold阈值
        this.threshold = tableSizeFor(initialCapacity);
    }
    /*将初始化容量转化为大于等于最接近cap的2的整数次幂
    |是或运算,>>>是无符号右移,空位0补齐
    以n = 011011,
    011011 >>> 1 = 001101 
    011011 | 001101 = 011111
    .....
    然后继续下去,最后得到最高位和后面的都是1,就能保证结果大于等于n,并且n为奇数,最后再加1.
    因为int为32位,所以最后肯定能让所有位都为1
    */
    static final int tableSizeFor(int cap) {
        //cap减一,是防止传进来的是2的整数次幂,减一后保证最后结果是cap本身
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    //如果没有传入填充因子,则使用默认的填充因子
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    //只默认了填充因子
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    //传入一个Map初始化
    public HashMap(Map<? extends K, ? extends V> m) {
        //使用默认填充因子
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        //s是长度
        int s = m.size();
        if (s > 0) {
            //如果哈希表没有初始化
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                //计算出来的t大于阈值,则用t初始化阈值
                if (t > threshold)
                    threshold = tableSizeFor(t);
            } //m的个数大于阈值,则进行扩容
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

其他方法

(table.length - 1) & hash

HashMap 根据 key 的 hashCode 计算 hash 值,知道 hash 值之后怎么确定 key 在数组中的位置呢,这里就用到了(table.length - 1) & hash;
首先使用(table.length - 1) 和 hash 进行与操作,不用担心数组越界。那为什么要数组长度减一呢?假设数组长度是 16,假设有两个 hashcode 是 8 和 9:
8 的二进制:1000
9 的二进制:1001
16 的二进制是:10000
8 & 16 = 10000
9 & 16 = 10000
这样出现了两个不同的 hashcode 在一个数组中,增加了查找的次数
如果 table.length - 1,也就是 16-1:
15 的二进制:1111
8 & 15 = 1000
9 & 15 = 1001

get
    //传入Key,返回Value
    public V get(Object key) {
        Node<K,V> e;
        //这里也能看到hashmap可以保存null
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    //传入Key的hash值和key的值
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //判断数组是否是null,数组长度是否大于0,取出来的结点是否为null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //先判断结点的hash值是否相同,再判断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) {
                //判断first是不是红黑树
                if (first instanceof TreeNode)
                    //调用TreeNode中的getTreeNode方法,我还没看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;
    }

红黑树

红黑树不是严格的平衡二叉树,红黑树比 AVL 树不平衡最多一层,查询上比 AVL 最多多一次比较。红黑树在添加和删除结点时比 AVL 减少旋转次数,旋转三次以内就会解决不平衡,而 AVL 树追求严格平衡,旋转次数很多。因此大多选用红黑树。

  • 树根:必须是黑色
  • 叶子节点:黑色(NULL)
  • 红色节点的子节点都是黑色(不存在两个红色节点连续)
  • 从任一节点到每个叶子节点路径包含相同数量的黑色节点

    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // 父节点
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // 前一个节点
        boolean red;  //颜色
        /*
        这个构造函数调用了super(),LinkedHashMap.Entry的构造函数中也是调用super();就回到了上面的Node类中:
        Node(int hash, K key, V value, Node<K,V> next) {}

        */
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * 返回这个节点的根节点,就是不断向上找
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                //根节点的父节点是null
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

        /**
         * 确保传进来的root节点是这个二叉树的根节点
         */
        static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
            int n;//n是HashMap的数组长度
            //验证传进来的参数是否合法,tab是HashMap的哈希表
            if (root != null && tab != null && (n = tab.length) > 0) {
                //上面解释过了,index是哈希表数组的索引
                int index = (n - 1) & root.hash;
                //如果是红黑树的结构,哈希表数组中存储的结点是红黑树的头节点,所以这里直接取tab[index]就是取出来红黑树的头节点,可以看上面的图
                TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
                //如果头节点和传进来的root不相同
                if (root != first) {
                    Node<K,V> rn;
                    //直接把root放进去
                    tab[index] = root;
                    TreeNode<K,V> rp = root.prev;//rp等于root结点的前一个结点
                    //如果存在下一个结点
                    /*
                    这里是这样:rp-->root-->rn 现在把root拿出来当红黑树的根结点了变成了:rp-->rn
                    因为是双向链表,需要:rp<--rn
                    */
                    if ((rn = root.next) != null)
                        //下一个结点rn的前驱结点设置为root的前驱rp<--rn
                        ((TreeNode<K,V>)rn).prev = rp;
                    if (rp != null)
                        //rp-->rn
                        rp.next = rn;
                    /*
                    这里变成了:root-->frist;null<--root<--frist
                    */
                    if (first != null)
                        first.prev = root;
                    root.next = first;
                    root.prev = null;
                }
                //checkInvariants()方法还没看,这里如果返回false就会抛出AssertionError错误,然后终止执行
                assert checkInvariants(root);
            }
        }

        /**
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         h:hash值   k:key   kc:缓存key?
         给定hash值和key找到这个节点
         */
        final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            //从节点p还是查找
            TreeNode<K,V> p = this;
            do {
                //ph:p节点的hash值; pk:节点p的key
                int ph, dir; K pk;
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                /*
                    这里能看出来,红黑树是根据hash值来判断一个节点应该去左边还是右边。这里可能会有个疑问,前面判断在哈希表数组索引也是用的hash值,那红黑树中所有的hash值不应该一样吗?其实,前面哈希表数组中判断的hash值是Node节点的hash值:Objects.hashCode(key) ^ Objects.hashCode(value);也就是key的hash值和value的hash值取异或,而这里用到的hash值是key的hash值,还不知道value是多少。
                */
                //h小于p节点的hash值,向左查找
                if ((ph = p.hash) > h)
                    p = pl;
                //h大于p节点的hash值,向右查找
                else if (ph < h)
                    p = pr;
                //判断key是否相同,相同就查找到了
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                //这是出现hash值相同但是key不同的情况?
                else if (pl == null)
                    //左子树是null就去右子树找
                    p = pr;
                else if (pr == null)
                    //左子树是null去右子树找
                    p = pl;
                //comparableClassFor方法是获取k的运行时类型,compareComparables方法先判断,key与运行时kc是同类型,在通过调用k和kc实现的Comparable接口的compareTo进行比较
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                //在右子树里面递归
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }

        /**
         * 从根节点开始查找
         */
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            //parent==null 就说明是根结点,否则就找到根结点再查找
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        /**
            比较两个对象的大小,不会返回0
         */
        static int tieBreakOrder(Object a, Object b) {
            int d;
            //比较类名,如果相同,调用本地方法为对象生成hashcode值,再继续比较
            if (a == null || b == null ||
                (d = a.getClass().getName().
                 compareTo(b.getClass().getName())) == 0)
                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                     -1 : 1);
            return d;
        }

        /**
         * 链表转成红黑树
         */
        final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                //把x在链表里面取出来,next指向下一个结点
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;//设置左右子树为null
                //如果x是第一个结点,也就是root为null的情况,将父结点指向null,颜色是黑色
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    //下面的代码和find函数差不多,就是找到k应该去的位置。
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);
                        TreeNode<K,V> xp = p;
                        //dir小于等于0去左边,大于0去右边。这里找到了应该去的位置
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            //旋转节点,保持平衡
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            //将根节点放进去
            moveRootToFront(tab, root);
        }

        /**
         * 将树转成链表
         */
        final Node<K,V> untreeify(HashMap<K,V> map) {
            Node<K,V> hd = null, tl = null;
            for (Node<K,V> q = this; q != null; q = q.next) {
                Node<K,V> p = map.replacementNode(q, null);
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

        /**
         * 插入元素
         */
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;//标记是否查找一次
            TreeNode<K,V> root = (parent != null) ? root() : this; //获取根结点
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    //如果K和PK通过COMPARATO比较之后,如果相同就进来,并且只会进来一次
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        //从左子树或者右子树中找到就返回
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);
                }
                //找到合适的位置,然后插入
                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    //创建一个新的节点
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

               /*
            删除结点
            1.如果删除的是红色结点则不影响性质
            2。如果删除的是黑色结点,那么路径上会少一个黑色结点,破坏了性质
         */
        final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
                                  boolean movable) {
            int n;
            if (tab == null || (n = tab.length) == 0)
                return;
            int index = (n - 1) & hash;
            //找到根结点
            TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
            //succ表示下一个结点,pred表示上一个结点
            TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
            //如果要删除根结点,直接将下一个结点提上来
            if (pred == null)
                tab[index] = first = succ;
            //否则就直接将当前结点的上一个结点指向当前结点的下一个结点
            else
                pred.next = succ;
            if (succ != null)
                succ.prev = pred;
            if (first == null)
                return;
            //根结点赋值到root
            if (root.parent != null)
                root = root.root();
            //红黑树结点太少,转换成链表返回
            if (root == null
                || (movable
                    && (root.right == null
                        || (rl = root.left) == null
                        || rl.left == null))) {
                tab[index] = first.untreeify(map);  // too small
                return;
            }
            TreeNode<K,V> p = this, pl = left, pr = right, replacement;
            /*
            找到结点之后,需要删除结点,红黑树删除结点分为几种情况:
            情况1:删除的结点左右子树都非空(按其他二叉树删除的方式处理,转变成其他的下面的三种情况)
            情况2:删除的结点左子树为空,右子树非空
            情况3:删除的结点右子树为空,左子树非空
            情况4:删除的结点左右子树都为空
            */
            //情况1
            if (pl != null && pr != null) {
                //这里s指向的是当前结点p的右节点
                TreeNode<K,V> s = pr, sl;
                //不断找要删除结点的右子树里面的最左结点,赋值给s
                while ((sl = s.left) != null) // find successor
                    s = sl;
                //交换要删除结点右子树的最左叶子节点s和要删除结点p的颜色
                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
                TreeNode<K,V> sr = s.right;
                TreeNode<K,V> pp = p.parent;
                //特殊情况,如果p结点的右结点s没有左孩子
                if (s == pr) { // p was s's direct parent
                    //直接交换p结点和s结点
                    p.parent = s;
                    s.right = p;
                }
                else {
                    TreeNode<K,V> sp = s.parent;
                    //还是交换s结点和p结点
                    if ((p.parent = sp) != null) {
                        if (s == sp.left)
                            sp.left = p;
                        else
                            sp.right = p;
                    }
                    if ((s.right = pr) != null)
                        pr.parent = s;
                }
                p.left = null;
                //如果s存在右结点,就将p设置为sr的父结点
                if ((p.right = sr) != null)
                    sr.parent = p;
                //p的左结点给s
                if ((s.left = pl) != null)
                    pl.parent = s;
                //p的父结点给s
                if ((s.parent = pp) == null)
                    root = s;
                else if (p == pp.left)
                    pp.left = s;
                else
                    pp.right = s;
                //如果s有右结点,则replacement等于右结点,否则为p
                if (sr != null)
                    replacement = sr;
                else
                    replacement = p;
            }
            //情况3
            else if (pl != null)
                replacement = pl;
            //情况2
            else if (pr != null)
                replacement = pr;
            else       //情况4
                replacement = p;
            //当p有孩子或者s有孩子,进行删除结点操作
            if (replacement != p) {
                TreeNode<K,V> pp = replacement.parent = p.parent;
                if (pp == null)
                    root = replacement;
                else if (p == pp.left)
                    pp.left = replacement;
                else
                    pp.right = replacement;
                p.left = p.right = p.parent = null;
            }
            //对红黑树进行调整
            TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
            //当p结点没有孩子,或者s结点没有孩子,进行删除操作
            if (replacement == p) {  // detach
                TreeNode<K,V> pp = p.parent;
                p.parent = null;
                if (pp != null) {
                    if (p == pp.left)
                        pp.left = null;
                    else if (p == pp.right)
                        pp.right = null;
                }
            }
            if (movable)
                moveRootToFront(tab, r);
        }

        /**
            红黑树扩容时调用拆分方法,将红黑树拆成两个链表
         */
        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;
                }
            }

            if (loHead != null) {
                //UNTREEIFY_THRESHOLD = 6  ,如果拆分后小于这个值就转成链表,否则就转成红黑树
                if (lc <= UNTREEIFY_THRESHOLD)
                    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)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }

        /* ------------------------------------------------------------ */
        // Red-black tree methods, all adapted from CLR
        //下面是左旋和右旋调整结点,在我另外一篇博客中已经将清楚了[算法导论学习笔记--红黑树](https://www.gwt.fun/articles/2017/08/26/1546585401831.html#%E6%97%8B%E8%BD%AC)
        //左旋
        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
                                              TreeNode<K,V> p) {
            TreeNode<K,V> r, pp, rl;
            if (p != null && (r = p.right) != null) {
                if ((rl = p.right = r.left) != null)
                    rl.parent = p;
                if ((pp = r.parent = p.parent) == null)
                    (root = r).red = false;
                else if (pp.left == p)
                    pp.left = r;
                else
                    pp.right = r;
                r.left = p;
                p.parent = r;
            }
            return root;
        }
        //右旋
        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
                                               TreeNode<K,V> p) {
            TreeNode<K,V> l, pp, lr;
            if (p != null && (l = p.left) != null) {
                if ((lr = p.left = l.right) != null)
                    lr.parent = p;
                if ((pp = l.parent = p.parent) == null)
                    (root = l).red = false;
                else if (pp.right == p)
                    pp.right = l;
                else
                    pp.left = l;
                l.right = p;
                p.parent = l;
            }
            return root;
        }
        /*
        插入结点后调整方法,插入结点遵循下面的规则:
        1、插入的结点重视红色
        2、如果插入结点的父结点是黑色,能保证性质
        3、如果是红色,则破坏了性质,必须进行重新染色或者旋转
        插入过程详解过程:https://www.gwt.fun/articles/2017/08/26/1546585401831.html#%E6%8F%92%E5%85%A5
        */
        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            x.red = true; //先设置插入的结点为红色
            //xp:x的父结点;xpp:x的父结点的父结点,也就是爷爷结点;xppl:爷爷结点的左节点;xppr:爷爷结点的右结点
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
                //如果x的父结点是null,表示x是根结点,直接返回x
                if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                //如果父结点是黑色或者不存在爷爷结点,就直接返回
                else if (!xp.red || (xpp = xp.parent) == null)
                    return root;
                //如果父结点是爷爷结点的左结点
                if (xp == (xppl = xpp.left)) {
                    //如果爷爷结点的右结点存在,并且该结点是红色
                    if ((xppr = xpp.right) != null && xppr.red) {
                        //这里结合图看的会更明白,把叔叔结点设置成黑色,父结点设置为黑色,爷爷结点设置成红色
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        //爷爷结点赋值给x,继续循环
                        x = xpp;
                    }
                    //爷爷结点的右结点不存在或者叔叔结点是黑色
                    else {
                        //判断x是否是父结点的右节点
                        if (x == xp.right) {
                            //x上升至父结点,并左旋
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            //x是左孩子,x的父结点设置为黑色,x的爷爷改成红色然后右旋
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                }
                else {  //将上面的过程反过来
                    if (xppl != null && xppl.red) {
                        xppl.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        if (x == xp.left) {
                            root = rotateRight(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateLeft(root, xpp);
                            }
                        }
                    }
                }
            }
        }
        /*
        删除结点后调整规则:
        1、如果删除红色结点,不破坏规则
        2、如果是黑色,就少了一个黑色
        
        https://www.gwt.fun/articles/2017/08/26/1546585401831.html#%E5%88%A0%E9%99%A4
        */
        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
                                                   TreeNode<K,V> x) {
            for (TreeNode<K,V> xp, xpl, xpr;;) {
                //删除后结点是null或者是根结点,不调整
                if (x == null || x == root)
                    return root;
                //x成为根结点,将x设置为黑色
                else if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                //如果x是红的,设置成黑
                else if (x.red) {
                    x.red = false;
                    return root;
                }
                //x是父亲的左孩子
                else if ((xpl = xp.left) == x) {
                    //x的兄弟是红色的
                    if ((xpr = xp.right) != null && xpr.red) {
                        xpr.red = false;
                        xp.red = true;
                        root = rotateLeft(root, xp);
                        xpr = (xp = x.parent) == null ? null : xp.right;
                    }
                    //没有兄弟,则x到父结点位置
                    if (xpr == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                        if ((sr == null || !sr.red) &&
                            (sl == null || !sl.red)) {
                            //如果x结点的兄弟是黑色的,并且左右结点都是黑色
                            xpr.red = true;
                            x = xp;
                        }
                        else {
                            if (sr == null || !sr.red) {
                                //x的兄弟是黑色,右结点是黑色,左结点是红色
                                if (sl != null)
                                    sl.red = false;
                                //将x的兄弟结点变成红色,然后右旋
                                //下面的不写了,就是那几个过程,看明白就行,代码看不看都可以
                                xpr.red = true;
                                root = rotateRight(root, xpr);
                                xpr = (xp = x.parent) == null ?
                                    null : xp.right;
                            }
                            if (xpr != null) {
                                xpr.red = (xp == null) ? false : xp.red;
                                if ((sr = xpr.right) != null)
                                    sr.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateLeft(root, xp);
                            }
                            x = root;
                        }
                    }
                }
                else { // 反过来的
                    if (xpl != null && xpl.red) {
                        xpl.red = false;
                        xp.red = true;
                        root = rotateRight(root, xp);
                        xpl = (xp = x.parent) == null ? null : xp.left;
                    }
                    if (xpl == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
                        if ((sl == null || !sl.red) &&
                            (sr == null || !sr.red)) {
                            xpl.red = true;
                            x = xp;
                        }
                        else {
                            if (sl == null || !sl.red) {
                                if (sr != null)
                                    sr.red = false;
                                xpl.red = true;
                                root = rotateLeft(root, xpl);
                                xpl = (xp = x.parent) == null ?
                                    null : xp.left;
                            }
                            if (xpl != null) {
                                xpl.red = (xp == null) ? false : xp.red;
                                if ((sl = xpl.left) != null)
                                    sl.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateRight(root, xp);
                            }
                            x = root;
                        }
                    }
                }
            }
        }

        /**
         * 从根结点开始检查红黑树,是否符合红黑树的性质
         */
        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
                tb = t.prev, tn = (TreeNode<K,V>)t.next;
            if (tb != null && tb.next != t)
                return false;
            if (tn != null && tn.prev != t)
                return false;
            if (tp != null && t != tp.left && t != tp.right)
                return false;
            if (tl != null && (tl.parent != t || tl.hash > t.hash))
                return false;
            if (tr != null && (tr.parent != t || tr.hash < t.hash))
                return false;
            if (t.red && tl != null && tl.red && tr != null && tr.red)
                return false;
            if (tl != null && !checkInvariants(tl))
                return false;
            if (tr != null && !checkInvariants(tr))
                return false;
            return true;
        }
    }

put(K,V)

终于看完了 TreeNode 类,现在继续看 HashMap。

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果tab是空或者长度为0,就扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果哈希表数组中是空,就创建一个结点放进去
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //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);
                        //如果链表长度大于等于8就变成红黑树,同理,红黑树小于6就转成链表
                        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;
                }
            }
            //更新value值
            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();
        afterNodeInsertion(evict);
        return null;
    }

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) {
            //超过Integer最大值,就不能加了
            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
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //调用了无参构造函数,使用默认容量16,阈值为0.75*16
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //如果新阈值为0,则重新计算,如果超过了Integer最大值,就直接赋值最大值
        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;
        //如果旧tab里面有数据
        if (oldTab != null) {
            //遍历每一个哈希表数组
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                //临时将结点赋值给e
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //如果e只有一个结点,就重新计算然后存到新tab里面
                    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;
                            /*
                            e.hash & oldCap,这个也非常的巧妙,刚在红黑树的split中看这个式子还没闷过来弯,在这里看明白了。(table.length - 1) & hash是查找索引,而这里没有减一。
                            这样就得出来两个值,0或者oldCap,这样就能拆成两个链表
                            
                            
                            */
                            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()

这个方法的作用是将链表转成红黑树

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //如果链表达到了转换成红黑树的阈值,但是tab的数量没到变成红黑树的阈值,也不会变化。MIN_TREEIFY_CAPACITY = 64
        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.hashcode()和 hash()

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1083 引用 • 3461 回帖 • 261 关注
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3169 引用 • 8208 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...