• java集合类史上最细讲解 - HashMap篇


    java集合类史上最细讲解 - HashMap篇

    1.HashMap的底层机制

    底层存放数据示意图:

    在这里插入图片描述

    k,v是一个Node实现了Map.Entry

    jdk8以上底层为数组+链表+红黑树


    2.HashMap源码解读

    解读代码:

    Map map = new HashMap();
    // 添加键值对
    map.put("no1","dahe");
    map.put("no2","zhangsan");
    // Key重复会进行替换
    map.put("no1","lisi");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    新建HashMap对象,我们步入看看

    首先,会进行初始化加载因子,加载因子的值为0.75

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
    
    ---
    
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    开始执行put方法,通过一通计算hash值,传入参数进入putVal方法

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    • 1
    • 2
    • 3

    putVal方法:(不要慌,详细的代码解读可以参见HashSet篇😁,接下来我们来debug看一下具体的代码执行过程)

    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;
        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;
            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);
                        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;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    此时的table表为空。我们进行resize操作

    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    
    • 1
    • 2

    老样子,按规则进行扩容(规则详见HashSet篇)

    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;
            }
            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;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    接下来,通过hash值计算table的某个位置有没有数据存在,如果没有的话,新建一个Node节点,挂在table数组上

    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    
    • 1
    • 2

    这样一来,第一个数据就添加成功啦!

    继续步入,直到第二个元素添加完成,关键来了,开始添加第三个元素

    步入步入,到达比较hash值的部分,由于新增的对象的hash值和第一个一致且key值相等,则执行e=p操作

    if (p.hash == hash &&
        ((k = p.key) == key || (key != null && key.equals(k))))
        e = p;
    
    • 1
    • 2
    • 3

    继续向下执行,会替换第一个键值对key所对应的值为新增的lisi

    if (e != null) { // existing mapping for key
        V oldValue = e.value;
        if (!onlyIfAbsent || oldValue == null)
            e.value = value;
        afterNodeAccess(e);
        return oldValue;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    分析完毕

  • 相关阅读:
    解决APP抓包问题【网络安全】
    kubernetes安全机制
    Python 批量修改文件名
    市场研究工具有哪些
    Ubuntu下载odbc驱动
    php-java-net-python-大学生兼职信息交流系统网站计算机毕业设计程序
    Coursera耶鲁大学金融课程:Financial Markets 笔记Week 02
    阿乐的葡萄
    基于单片机的智能电子鼻的设计
    从零点五开始的深度学习笔记——VAE(Variational AutoEncoder) (三)VAE的简单实现
  • 原文地址:https://blog.csdn.net/Gherbirthday0916/article/details/125999267