HashMap部分源码分析

方法源码解析

插入元素方法(putVal())

putVal源码流程图链接

    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 判断当前映射(map)中的数组是否初始化
        if ((tab = table) == null || (n = tab.length) == 0)
        	// 没有初始化则调用resize()方法初始化并将初始化后的容量赋值给变量n
            n = (tab = resize()).length;
        // 计算待插入元素下标,并判断待数组中该处下标的位置的值是否为null
        if ((p = tab[i = (n - 1) & hash]) == null)
        	// 如果是null,则在新建一个该元素的节点对象存入该下标处
            tab[i] = newNode(hash, key, value, null);
        else {	// 数组中该处坐标已存在节点,需要进一步判断
            Node<K,V> e; K k;
            // 通过判断待插入元素与同坐标下的第一个节点的hash值和key值(分为基本数据类型判断和引用数据类型判断)是否相同
            // 即是否发生hash冲突
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            	// 相同则将对象e的指针指向数组中该下标处的节点
                e = p;
                // 判断下标处的节点是不是红黑树
            else if (p instanceof TreeNode)
            	// 是红黑树,则将节点p强转成红黑树,并将调用putTreeVal方法遍历该红黑树查看是否存在该节点,
            	// 如果存在则直接返回该节点,不存则创建新的节点到红黑树中并返回null
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	// 循环链表中的节点,判断链表中是否有已存在待插入的节点
                for (int binCount = 0; ; ++binCount) {
                	// 判断当前节点p的下一个节点是否是null,即当前是否循环到了链表最后一个节点
                    if ((e = p.next) == null) {
                    	// 是,则创建一个新的节点并插入到p的后边
                        p.next = newNode(hash, key, value, null);
                        // 判断当前链表是否达到树化的阈值
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 判断当前节点是否和与待插入节点相同,相同则节点对象e即是已存在的相同节点,并跳出循环
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 不同,则将e指向的下一个节点复制给p,继续循环
                    p = e;
                }
            }
            // 判断e是否是null,即链表中是否存在和待插入元素相同的节点
            if (e != null) { // existing mapping for key
            	// 存在,将已存在节点的value值复制给变量oldValue
                V oldValue = e.value;
                // 判断是否要保存重复节点的标识为以及已存在节点的value值是否为null
                if (!onlyIfAbsent || oldValue == null)
                	// 不保存重复节点或者已存在节点的value值为null,则将待插入元素值替换已存在节点的value
                    e.value = value;
                // 该方法为空方法,无实际操作
                afterNodeAccess(e);
                // 返回旧value值
                return oldValue;
            }
        }
        ++modCount;
        // 判断新增一条数据后当前map的元素数量是否超过了所设置的容量(threshold)阈值,超过则调用resize方法扩容
        // threshold的取值有两种:
        // 1)HashMap初始化时用户设置,HashMap会调用tableSizeFor方法将该值转换成大于当前值的2的n次方值并赋值给threshold
        // 2)未设置初始值,HashMap会设置threshold = 16 * 0.75 = 12
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        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
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        // 获取当前HashMap对象的数组长度即bucket(桶)的数量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 获取当前扩容阈值,如果map未进行初始化则oldTab=null,则当前的threshold=0,即oldThr=0
        int oldThr = threshold;
        int newCap, newThr = 0;
        // 判断当前Map是否为空(是否初始化)
        if (oldCap > 0) {
        	// 当前map不为空(已初始化并且有值)
        	// 判断当前map的bucket数量是否大于等于最大限值(1<<30)
            if (oldCap >= MAXIMUM_CAPACITY) {
            	// 是,则将当前扩容阈值设置为最大限值(1<<31-1)
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 如果当前bucket数量为达到阈值,扩大一倍后小于最大阈值,且当前bucket量大于等于默认量16则扩容两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        // 判断当前扩容阈值是否大于0,即map对象是未初始化且设置了初始容量(initialCapacity),所以当前的threshold为initialCapacity转换而来
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
       	// 当前map对象完全未初始化,需要设置默认值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 判断当前map是否设置了新的扩容阈值
        if (newThr == 0) {
        	// 没有设置则使用新的容量*加载因子的公式进行计算得出
            float ft = (float)newCap * loadFactor;
            // 判断新的容量值和新的扩容阈值是否都小于最大阈值且新的扩容阈值也小于这个最大阈值,
            // 以此判断新的阈值是否要使用map的bucket上限(int值的上限)
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        // 将最新的扩容阈值赋值给当前map的threshold变量
        threshold = newThr;
        // 扩容操作
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    // 判断当前bucket是否只有一个节点(是否是个链表)
                    if (e.next == null)
                    	// 是,则将该节点的hash值进行计算后放入新table对应的位置
                        newTab[e.hash & (newCap - 1)] = e;
                    // 判断当前bucket是不是一个树节点
                    else if (e instanceof TreeNode)
                   		// 将当前bucket中的节点强转成树节点类型并调用其split()方法将该节点重新结算后放入新的table中
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    // 判断走到这则证明当前bucket中的节点为链表节点
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        // do while循环将将链表转换成两个链表
                        // 扩容后,当前位置链表中元素要么在新链表中位置不变,要么是在当前位置+oldCap的位置上,故需要分成两个链表分别放入新的table中的对应位置中
                        do {
                            next = e.next;
                            // 判断当前节点应该进入lo还是hi链表
                            if ((e.hash & oldCap) == 0) {
                            	// loHead和loTail同时指向第一个节点,loTail执行链表延伸操作,loHead不动作为链表的头节点
                                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;
    }

调整初始容量方法(tableSizeFor())

该方法将传入的容量值cap转换成接近该值的较大的2幂值

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int 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;
    }
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值