HashMap存入数据时源码阅读

首先java版本1.8
首先确定的是,HashMap的存储结构
这里写图片描述
约定在前面的是桶
在桶后面的链表是bin
源码

//hashmap中的put方法
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        //调用的是object的hashcode,所以我们要修改时要将key的hashcode修改,以及在下面putVal中会调用到equals方法。
        //>>> ,>> ,<< 是java中仅有的移位运算符.>>>是无符号右移
    }


 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)
            n = (tab = resize()).length;
            //此处是||,所以分为两种情况,第一种table为空,初始化table,第二种将tab.length赋给n
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);//判断通过hash运算后的tab上是否有值,如果没有,就新建
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;//如果两个key相同,将p给赋给e,会在下方判断e是否为空,如果不为空,将原来的oldVal = newVal;
            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);//从当前bin中遍历,遍历到最后,在末尾newNode,插入值
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        //此处已经大于TREEIFY_THRESHOLD,所有链表变成红黑树
                            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
            //key值存在,就替换
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)//扩容
            resize();
        afterNodeInsertion(evict);
        return null;
    }

还有具体扩容变换过程,可以参考以下博客
HashMap的扩容及树化过程
具体参考了以下几篇博客:https://blog.csdn.net/lianhuazy167/article/details/66967698
https://blog.csdn.net/fan2012huan/article/details/51088211
https://blog.csdn.net/u013412772/article/details/80748604
看了一下午的源码,终于算有个大致了解了

猜你喜欢

转载自blog.csdn.net/qq_32296307/article/details/81103436