hashmap源码分析

hashmap源码分析

底层原理

hashmap底层是一个Node<K, V> 的数组,里面的K V也即我们想要存的key, value,但是具体存在table的哪个位置索引,则需要我们用hash值进行计算。hashmap的hash计算方法如下:也即先计算key的hashcode,再将这个hashcode结果和hashcode高位进行异或。这样做的原因是让高位和低位都参与最后的计算(index = hashcode & n-1)

static final int hash(Object key) {
         int h;
         return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
     }

如果发生冲突怎么办呢?当发现打算放的位置非空,首先会比较该位置所放的节点的key以及hash值与当前节点是否相同,如果相同则更新原节点的值;如果不同则插入到原节点的next节点(可能next也非空,那就一直向后遍历,直至next非空为止)。如果原节点后面已经放了8个next节点(Node),则需要把链表调整为红黑树(TreeNode),具体调整算法下面会介绍。
title

Node结构

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

        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;
            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. 红黑树是平衡二叉搜索树(左孩子<根节点<右孩子,且左右高度差不超过1)
  2. 节点是红色或者黑色
  3. 根节点是黑色
  4. 每个叶子节点是黑色的空节点。
  5. 每个红色节点的两个子节点都是黑色的。
  6. 从任意节点到根节点的所有路径都包括相同个数的黑节点。
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //如果tab为空或者tab长度小于64,则需要重新调整tab的大小
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {//如果tab[index]非空,则将tab[index]及其后面的所有节点转化为treeNode节点。(将Node单向链表,转化为TreeNode双向链表)
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;//hd指向当前节点需要插入的
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);//将链表转化为红黑树
        }
    }
    //将链表转化为红黑树,this指向当前节点插入的位置,tab是链表
    final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;//root指向红黑树的根节点
            for (TreeNode<K,V> x = this, next; x != null; x = next) {//从链表当前节点开始遍历
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) {//如果红黑树根节点为null,则将链表中的当前节点置为根节点,根节点颜色置为黑色。
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {//已经有根节点了,就判断当前节点位于左分支还是右分支。
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    //从树的根节点开始遍历。
                    //p指向树中的当前节点。
                    //x指向链表中的当前节点
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        //通过比较树中的当前节点(p)和链表(x)的key.hash来判断x放入p的左侧还是右侧分支。
                        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);
                        //xp指向当前节点(x)需要插入p那一侧的叶子节点的根节点
                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            //插入x节点后,红黑树需要重新调整平衡
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }
        
        //红黑树插入节点后,需要重新调整平衡
        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
            //修改当前节点颜色为红色(它的父节点是叶子节点——黑色)
            x.red = true;
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
                //xp表示当前节点的父节点,父节点为空,则说明红黑树中只有当前节点
                if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                else if (!xp.red || (xpp = xp.parent) == null)//xpp指向父节点的父节点(为空);此时只有两层,也不需要调整。
                    return root;
                //插入节点的父节点位于左侧
                /**
                  xpp
                 /
                xp
                /\
               p  p
                */
                if (xp == (xppl = xpp.left)) {
                    if ((xppr = xpp.right) != null && xppr.red) {
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                    /**
                      xpp
                     /
                    xp
                     \
                      p
                    左旋
                    */
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            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);
                            }
                        }
                    }
                }
            }
        }
   

增删改查

put

 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;
        if ((tab = table) == null || (n = tab.length) == 0)
            // table还未创建,则新建之
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 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))))
                // hash 位置上已经存在该key,则后续判断是否需要修改value
                e = p;
            else if (p instanceof TreeNode)
                // 红黑树节点,则将待插入节点插入到红黑树
                // 如果插入过程中发现key已经存在于红黑树中,则后续判断是否需要修改value
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                // 链表,则插入链表末尾
                // 遍历链表过程中如果发现key已经存在,则后续判断是否需要修改value
                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
                            // 链表长度超过一定长度(默认为8)则将链表转换为红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 发现key已经存在于链表中了
                    p = e;
                }
            }
            // table中已经存在该key了,根据onlyIfAbsent判断是否需要修改value
            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;
    }

title

remove

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
    
    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;
            //先找到需要被删除的节点,用node表示
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                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);
                }
            }
            //找到了被删除的节点,再remove
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)//调用红黑树的remove方法
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;//如果tab[index]只有一个元素,不是链表,则用node的next放入node的位置
                else
                    p.next = node.next;//链表,则用node.next放入node原来的位置
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

get

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    
        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,检查第一个节点的key值是否相等
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {//检查next节点
                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;
    }

扩容策略

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;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 通常情况下threshold成倍扩展
                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 = newTab;
        // 如果不是初始化的resize,就需要重新hash了。
        if (oldTab != null) {
            // 根据oldCap遍历整个table
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        // 如果是单独的一个节点,则重新hash到新table中
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        // 如果是红黑树则分裂红黑树
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order 保持原来的顺序,否则多线程同时resize会出现jdk1.7中的死链问题
                        // 对链表节点进行重新Hash,具体Hash算法下面详解
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            // oldCap就是新增的高位,相与 == 0则节点还应放在原下标
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else { // 相与 != 0 则节点应该放在 原下标+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; // 应该放在原下标的节点组成的链表
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead; // 应该放在 原下标+oldCap 位置的节点组成的链表
                        }
                    }
                }
            }
        }
        return newTab;
    }

无论是链表还是红黑树,其中节点在resize过后都需要重新重新hash,但是Java8中重新Hash设计的非常巧妙。举例说明,假设table从16扩展为32,具体变化为:
title
元素在重新计算hash之后,因为n变为2倍(capacity << 1),那么n-1的mask范围在高位多1bit(红色),因此新的index就会发生这样的变化:
title
因此,我们在扩充HashMap的时候,不需要重新计算hash,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”。

参考:
https://www.cnblogs.com/snowater/p/7742287.html
https://www.cnblogs.com/williamjie/p/9099141.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值