java基础-集合-HashMap(JDK20)学习

文章目录

    • TODO PUT方法原理图
    • hash
    • putVal
    • resize

TODO PUT方法原理图

hash

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

putVal

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // HashMap中的初始化数组table[],是一种懒加载的模式
        if ((tab = table) == null || (n = tab.length) == 0)
        	// 如果table为null,则通过resize()方法对table数组进行初始化,resize()也是扩容的方法
            n = (tab = resize()).length;
        // 通过hash方式,找到key所对应的数组的节点,然后把该数组节点赋值给p,
        if ((p = tab[i = (n - 1) & hash]) == null)
        	// 如果通过hash所算出来的数值节点为null,则通过newNode(Int hash,K key,V value,Node node)
        	// 初始一个新的node节点,然后把该值放到对应的数组中
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果通过哈希所算出来的数组不为空,即table[[i = (n - 1) & hash]不为空。
            // 且该节点的key是与我们即将要存的key相同,则获取该节点即e=p
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果该节点的key与我们不相等,且是红黑树,则通过红黑树的方式,把key-value存到红黑树中
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	// 如果是链表的,把key-value插到链表尾,该方式是链表的尾插入法
                for (int binCount = 0; ; ++binCount) {
                	// 遍历该链表,找到尾部,然后把尾部的next指向新生成的对象
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 如果该节点上的key与我们想要put进去的值相同跳出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 如果e不等于null,则说明HashMap中存在与我们即将要存进去的key相同,
            // 然后把节点中的值进行替换,即e.value=value,并放回旧的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=capacity * loadfactor,即数组初始化长度*负载因子,如果
        // this.loadFactor = DEFAULT_LOAD_FACTOR; 默认DEFAULT_LOAD_FACTOR=0.75
        // 如果HashMap中的存的数据,大于数组长度的四分之三,就要进行扩容
        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;
        // 如果原table不为空
        if (oldCap > 0) {
        	// 原容量大于1 << 30时返回Integer.MAX_VALUE不能扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 原容量小于1 << 30且原容量大于等于16时,将原容量扩容2倍,同时将阈值(threshold)也扩大2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        // 如果通过构造方法设置初始容量,构造方法中会计算threshold,此时原table为空, 进入此判断,threshold作为table的实际大小
        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);
        }
        // 计算指定了initialCapacity情况下的新的 threshold
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        // 初始化table或者扩容, 实际上都是通过新建一个table来完成
        @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) {
                	// table中存放的只是Node的引用,这里将oldTab[j]=null只是清除旧表的引用, 真正的node节点还在, 只是现在由e指向它
                    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指向该引用,在while判断条件中使用
                            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);
                        // 将loHead放入原下表桶
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // 将hiHead放入拆分后的新下表
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

你可能感兴趣的:(java,学习,哈希算法)