HashMap源码学习

1.hashmap原理讲解

2.put方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        //tab :当前haskmap的散列表
        //p:表示当前散列表的元素
        //n:表示散列表的长度
        //i:表示路由寻址 结果
        Node<K,V>[] tab; Node<K,V> p; int n, i;        
        //延迟初始化逻辑,第一次调用putVal方法时初始化hashmap对象中最耗内存的散列表
        if ((tab = table) == null || (n = tab.length) == 0)
            //resize():hash的扩容方法
            n = (tab = resize()).length;
            
        //最简单的一种情况:寻址到的桶位 刚好时null,直接将<k,v>封装到node节点里面去
        /*
         *为什么是(n - 1) & hash:与运算保证获取到的下标一定在0-(n-1)之间的一个数,
         *因为n为table的长度,下标最长为n-1,因此用n-1
        **/
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
            
        else {
        //e:node临时元素,e不为null的话,找到了一个与当前要插入的<k,v>一致的key的元素
        //k:临时的key
            Node<K,V> e; K k;
            //表示当前桶位置的元素与你要插入的元素的key值一样,表示后续要进行替换操作
            //这里比较key用到了==和equals,表示内存地址或者值一样都认为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);
                        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;
                }
            }
            //e不为null的话,找到了一个与当前要插入的<k,v>一致的key的元素,进行替换
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //modCount:整个散列表的结构被修改的次数,替换node元素的value不算在内
        ++modCount;
        //插入新元素,size自增,到达扩容阈值,则触发扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
复制代码
2.1 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.
     *
     * 为什么需要扩容?
     * 为了解决hash冲突导致的链化影响查询效率,扩容可以缓解此问题
     *
     * 红黑树这么好为什么一开始不使用它而选择链表呢?
     * 链表结构简单,树占内存,且红黑树的插入和删除需要重新平衡,这样效率反而没有链表效率高
     * @return the table
     */
    final Node<K,V>[] resize() {
        //oldTab:扩容前的hash表
        Node<K,V>[] oldTab = table;
        //oldCap:扩容前table数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //oldThr:扩容前的hash表的扩容阈值
        int oldThr = threshold;
        //newCap:扩容后table数组的长度
        //newCap:新的扩容阈值
        int newCap, newThr = 0;
        // 条件成立,说明hashmap中的散列表已经初始化了,这里是一次正常的扩容
        if (oldCap > 0) {
            //扩容之前的table数组已经到达最大阈值,不再进行扩容了,
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //oldThr左移一位进行扩容,相当长度于x2,
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //oldCap == o 说明hashmap的散列表是null 以下三种情况会进来
        //1.new HashMap(initialCapacity,loadFactor)
        //2.new HashMap(initialCapacity)
        //3.new HashMap(map),这里的map有数据
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //oldCap == o ,oldThr == 0
        //通过new HashMap()进来的
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;//16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//12
        }
        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"})
        //先根据计算好的table长度,创建出一个新的数组
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 扩容之前,table不为null
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                //e:临时node节点
                Node<K,V> e;
                //当前节点不为空
                if ((e = oldTab[j]) != null) {
                    //另旧数组的当前节点为null,方便GC回收
                    oldTab[j] = null;
                    /* 第一种情况:e,next为空,说明此节点只有一个值,并发生过hash碰撞,
                     * 所以直接计算当前位置的值在新数组中的索引位置(e.hash & (newCap - 1)),
                     * 扔进新数组。
                     */
                    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;
    }
复制代码

3.get方法

4.remove方法

5.replace方法

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享