HashMap数据结构分析(1.8)

时间:2019-10-22
本文章向大家介绍HashMap数据结构分析(1.8),主要包括HashMap数据结构分析(1.8)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

看了下HashMap的源码,做下记录,首先还是先从流程图开始

下面用代码分析下方法

    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;
            //和该处节点的 hash 相同并且 key相同
            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);
                        //大于等于7 转为树节点
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果链表不是尾部节点,并且是否遇到了key和hash都相同的
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 找到了 key和value都相同的节点
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                // value不为null 并且 onlyIfAbsent为false 就重新赋下值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 一个待实现的方法,hashMap无用
                afterNodeAccess(e);
                // 结束
                return oldValue;
            }
        }
        //结构更改的计数,为了在迭代中快速判断是否被修改了 而抛出异常
        ++modCount;
        // 长度++,扩容阈值
        if (++size > threshold)
            resize();
        //一个待实现的方法,hashMap无用
        afterNodeInsertion(evict);
        return null;
    }

原文地址:https://www.cnblogs.com/june777/p/11715018.html