美文网首页
HashMap源码学习

HashMap源码学习

作者: 摸摸脸上的胡渣 | 来源:发表于2020-02-15 13:14 被阅读0次

    hash()方法

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

    高低16位先做一个异或,就是保证既能拥有低16位数据的特征,又有高16位数据的特征,相当于能让hash值更加离散。

    putVal()方法

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                       boolean evict) {
            //tables的另一个引用
            Node<K,V>[] tab; 
            Node<K,V> p; 
            int n, i;
            //懒加载
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            //懒加载
            //根据hashcode的高低16位异或 再和 capacity-1按位相与 得到tables[]对应的下标
            //如果为空,就说明没有发生碰撞,直接占坑
            //如果不为空,那么就找到了p,即对应的坑头
            if ((p = tab[i = (n - 1) & hash]) == null)
                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))))
                    e = p;
                //如果坑头不是目标节点,且坑头是TreeNode,那么就说明链表已经变成了红黑树,要向树中继续插入或者寻找节点
                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,就要变成红黑树
                            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;
                    }
                }
                //如果目标节点已经存在
                //替换为新值,返回旧值
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    //LinkedHashMap会重写这个方法,完成排序操作
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            //fail-fast的保障机制
            ++modCount;
            //判断是否超过了阈值
            if (++size > threshold)
                //扩容吧您馁
                resize();
            //LinkedHashMap会重写这个方法,完成排序操作
            afterNodeInsertion(evict);
            //插入成功,返回null
            return null;
        }
    

    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
         */
        
        /**
        承担着初始化,和double容量的任务
        扩容结束后,要不坑位不动,要不坑位double
        */
        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;
                }
                //如果扩容后小于最大值,那么就把阈值也double
                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 = newTab;
            //遍历旧tables,分配旧节点
            if (oldTab != null) {
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;
                        //如果只有坑头,那就很好处理了,直接hash完塞进新tables即可
                        if (e.next == null)
                            newTab[e.hash & (newCap - 1)] = e;
                        //如果是个红黑树节点,那就调用split对树节点完成分发
                        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;
                                //==0说明不用动,还继续放j位置就行
                                if ((e.hash & oldCap) == 0) {
                                    if (loTail == null)
                                        loHead = e;
                                    else
                                        loTail.next = e;
                                    loTail = e;
                                }
                                //!=0说明之前把hash值的左边几位放弃掉了,本次要补回来,放置在j+oldCap的位置
                                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;
        }
    

    remove()方法

    /**
         * Implements Map.remove and related methods.
         *
         * @param hash hash for key
         * @param key the key
         * @param value the value to match if matchValue, else ignored
         * @param matchValue if true only remove if value is equal
         * @param movable if false do not move other nodes while removing
         * @return the node, or null if none
         */
        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) {
                    //如果是树
                    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;
                    //LinkedHashMap会重写这个方法,完成排序操作
                    afterNodeRemoval(node);
                    return node;
                }
            }
            return null;
        }
    

    get()方法

    其实和remove()方法的查找过程基本一致,就是先判断key的地址是否相等,相等的话就返回true,如果不相等的话,只能代表物理地址不一致,并不代表业务含义不一致,所以还要调用equals()方法进行业务含义的判断,两者有一个相等,即可认为是相等的。

    相关文章

      网友评论

          本文标题:HashMap源码学习

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