HashMap源码剖析03_resize()、remove()、get()方法详解

 /**
     * 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.
     * 为什么需要扩容?
     * 哈希冲突所导致的链化比较严重,查找时间复杂度退化为O(N),扩容可以缓解
     * @return the table
     */
    final Node<K,V>[] resize() {
    	//oldTab:扩容之前的哈希表
        Node<K,V>[] oldTab = table;
        //oldCap:扩容之前table数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //oldThr:扩容之前的阈值,触发本次扩容的阈值
        int oldThr = threshold;
        //newCap:扩容之后table数组的大小
        //newThr:下次再次触发扩容的条件
        int newCap, newThr = 0;
        //说明hashmap中的散列表已经初始化过了,是一次正常扩容
        if (oldCap > 0) {
        	//扩容之前的数组大小已经达到最大阈值,则不扩容且设置下次扩容条件为int最大值
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //oldCap左移一位实现翻倍,并且赋值给newCap,newCap小于最大值限制并且扩容之前阈值>=16,这种情况下则下一次扩容的阈值翻倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //oldCap == 0,说明hashmap中的散列表还未初始化
        //oldThr > 0原因:
        //通过new HashMap(initCap,loadFactor)
        //通过new HashMap(initCap)
        //通过new HashMap(map)并且map有数据
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //oldCap == 0,说明hashmap中的散列表还未初始化
        //oldThr == 0,new HashMap()
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;//16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//12
        }
        //不满足oldCap >= DEFAULT_INITIAL_CAPACITY
        //通过newCap和loadFactor重新计算出newThr
        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;
        //说明hashmap本次扩容之前table不为null,有数据
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
            //当前node节点
                Node<K,V> e;
                //当前桶位中有数据,但是是单个数据还是链表还是红黑树并不知道
                if ((e = oldTab[j]) != null) {
                //方面jvmGC时回收内存
                    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 {
                                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方法用于从映射中删除指定键值对

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
/**
     * Implements Map.remove and related methods.
     *
     * @param hash 键的hash值
     * @param key 键值对的键
     * @param value 键值对的值
     * @param matchValue 如果为true,当待删除的键值对的值等于value时删除
     * @param movable 如果是false,那么在删除时不要移动其他节点
     * @return 返回删除节点,如果不存在就返回null
     */
    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;
        //如果哈希数组非空且长度大于0
        //并且根据键的哈希值计算出的哈希桶数组对应位置的存储元素不为空
        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对象赋值给node
                node = p;
                //如果哈希桶里的元素不是要删除的元素
                //就判断是否有哈希碰撞
                //那么就需要分为链表和红黑树两种情况
            else if ((e = p.next) != null) {
            //如果p是TreeNode类型的
                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);
                }
            }
            //如果node不为空说明找到了要删除的Node节点
            //并且matchValue为false
            //或者matchValue为true,并且node的value等于参数中的value
            //或者matchValue为true,并且value放法的equals返回true
            //则可以执行删除操作
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //如果node是treenode类型的,则从树中删除
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //如果node==p,在index位置存储node的后继节点
                else if (node == p)
                    tab[index] = node.next;
                else
                //如果既不是treenode类型,又等于节点p
                //就修改链表使p的后继节点等于node的后继节点
                    p.next = node.next;
                    //修改结构性变化的次数
                ++modCount;
                //键值对数量-1
                --size;
                afterNodeRemoval(node);
                //返回node节点
                return node;
            }
        }
        return null;
    }
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
                ((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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值