初见HashMap源码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Ybt_c_index/article/details/84942123

这篇文章算是json那篇的番外吧,毕竟是为了搞清楚那件事,才引出了这件事。

本文只是简单的看了一下java 8的HashMap源码,大概只详细的看了两个方法,并且参考了几篇源码文章:
https://blog.csdn.net/soga613/article/details/78958642
http://www.importnew.com/28263.html

那么我们就开始吧。

简介

翻开源码,首先我们会看到有着篇幅巨大的注解。
在这里插入图片描述
开头就描述了HashMap不保证map中的顺序;第二段主要强调了迭代性能优先时,不要将初始容量设置的太大;第三段主要讲了两个重要参数:初始容量负载因子,负载因子是判断扩容的主要标准;第四段主要讲述负载因子的默认值为(.75),并解释了为什么这么设置,以及容量超过最大值上限时,不再重新hash;等等等(我们只需要了解这么多就可以继续接下来的内容了)。

接着我们又能看到另一大串注解。
在这里插入图片描述
主要讲述了map中,通常是以hash表的形式存在的,但是当每个位置的链表过大时,他就转化为一个树形结构,也就是红黑树(本文不讨论,后续更新)。在树结构中通常也是以hashCode为主进行排序,但如果两个元素符合"class C implements Comparable<C>"时,就会按照它们的compareTo方法排序。等等等等。

所以这段注解主要是为了讲述java 8新增的红黑树的相关内容。

然后我们就开始看具体的方法代码。

首先是HashMap的构造函数

public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        // MAXIMUM_CAPACITY的值为1073741824(2^30)
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        // 负载因子                                       
        this.loadFactor = loadFactor;
        // 计算阈值,超过这个值,就需要扩容
        this.threshold = tableSizeFor(initialCapacity);
    }

而这个计算阈值的方法就是一个非常好的算法

/**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

它的作用是返回据传入值最近的且比传入值大的2的n次方。
比如我们传入3,它返回4;传入6,返回8,传入12,返回16等等。

但是我们看到,在构造函数中,并没有初始化map,这个操作是在对应的putVal方法中进行的。

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;
        // 初始化tab数组
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果tab中之前的hash映射为空,则新建一个node
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        // 已有hash的情况    
        else {
            Node<K,V> e; K k;
            // p的hash有映射,且key值正好相等,那就是之前有对应key
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果p是树节点,涉及红黑树,忽略    
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            // p的hash有映射,但是这里是一个链表,所以需要遍历
            else {
                for (int binCount = 0; ; ++binCount) {
                    // 链表中没有对应key,新建node
                    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,则e值不为空,进行下面的覆盖操作
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // key值之前存在,进行覆盖操作,并返回旧值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        // 记录HashMap结构被修改的次数,在迭代的时候用
        ++modCount;
        // 如果发现容量超过阈值,则进行扩容
        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;
        // 旧表非空时
        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
        }
        // 如果旧表容量为0,但旧的阈值大于0(删除到容量为0的情况)
        else if (oldThr > 0) // initial capacity was placed in threshold
            // 新容量使用旧阈值
            newCap = oldThr;
         // 初始化,使用默认值   
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY; // 16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
        }
        // 新阈值为0时,第二种情况,用负载因子重新计算
        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];
        // 扩容后的tab
        table = newTab;
        // 如果旧tab非空,进行数据迁移
        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);
                    // 如果该元素是一个链表,将该链表分成两个链表,主要根据链表对应值的hash值确定    
                    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;
                            // 计算hash值
                            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);
                        // 原hash对应链表
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // 原hash+旧表容量的链表
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

重点说一下(e.hash & oldCap) == 0,因为容量翻倍后,之前hash对应的链表中就会分为两派,举例,之前的容量为16,hash为3的元素存在链表,链表中存的值有hash为3和19的,但是它们都在这个元素中,hash为19是因为容量限制,所以只能放在这里,但是当容量翻倍为32时,hash为19的值就有自己的在hash tab中的位置了,所以之前的一个链表分化为两个链表。这里偷一张图。
在这里插入图片描述

所以其实(e.hash & oldCap)就是计算新增的那个bit位是0还是1,也就是它应该属于原hash,还是扩容后的hash。


get

到这里,我们将主体的两个方法的源码看完了,还有一个get方法的源码,不过其实也很简单。

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // tab非空才会取到值
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // tab元素下对应hash中的第一个node
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 需要在对应链表中找值    
            if ((e = first.next) != null) {
                // 红黑树,走对应方法
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 遍历链表取值,取不到就返回null    
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

暂时就将HashMap的源码看到这里,已经够解决我之前的问题了。

猜你喜欢

转载自blog.csdn.net/Ybt_c_index/article/details/84942123
今日推荐