HashMap源码学习(JDK1.8)

今天撸了一下Java8的HashMap源码,总算搞清楚了一点点,所以Mark一下(有理解不对的地方希望有大佬指出)


先看一下HashMap的存储结构,先对HashMap的存储结构有一个初步认识对源码分析有很大好处。
在这里插入图片描述
上图取自CS-Notes
上图的0-15可以看做是16个桶,HashMap初始桶的数量为16,然后下面吊着的是桶上面的链表。


还是先看看结点的存储结构吧:

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
}

Node存储着一个键值对,还有该键对应的hash值,还有一个next字段,从这里可以看出Node是一个链表。


然后再看HashMap中有这么一个字段

/**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

这个字段其实就对应着上面那个图的数组,也就是数组的每一个位置当做一个桶,一个桶存放一个链表,同一个链表中存放着key相同的Node。Java7解决冲突的办法是拉链法,而Java8是拉链法加红黑树。当链表中的结点数大于树化阈值(TREEIFY_THRESHOLD=8)时,转化为一颗红黑树,以提高效率。


然后再来看几个字段

    //The default initial capacity - MUST be a power of two.
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

默认初始容量(桶的数量)为16,从注释还可以知道,这个值必须是2的幂次方

 // The load factor used when none specified in constructor.
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

默认加载因子为0.75,当调用没有指定加载因子的构造方法时,加载因子取0.75。加载因子在扩容的时候会用到。


然后看一下putVal()方法和resize()方法吧(今天只仔细看了这两个方法)
putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)方法由put(K key, V value)方法调用

/**
     * Implements Map.put and related methods  //put()方法调用该方法
     *
     * @param hash hash for key			//key的hash值
     * @param key the key			
     * @param value the value to put		//value
     * @param onlyIfAbsent if true, don't change existing value  //如果为true,则当key相同时,不覆盖原来的value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none  //如果该key之前已经存在,则返回之前的value,否则返回null
     */
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)	//如果桶的数量为空,就resize()
            n = (tab = resize()).length;			//重新调整桶的数量,并把新的桶的数量赋值给n
            //i=(n-1)&hash等价于hash%n,即key的hash值取余桶的数量,目的是key对应的桶的下标,下标赋值给i,然后这个桶的引用赋给p,如果这个桶还没被占领,则if判断为真
        if ((p = tab[i = (n - 1) & hash]) == null)		
            tab[i] = newNode(hash, key, value, null);		//直接把键值对放在这个桶中,第四个值为null,说明Node的next为null
        else {	//否则这个桶已经被占领
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) //如果这个桶里放的键值对的键和准备放进来的键值对的键相等
                e = p;		//将该键值对的引用赋给e
            else if (p instanceof TreeNode) //否则,如果该Node是TreeNode的实例,则表明这个桶后面已经是一颗红黑树,而不是链表
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//如果e!=null,表明红黑树里面已经存在该key
            else {		//否则该桶上吊着的是个链表
                for (int binCount = 0; ; ++binCount) {		//循环遍历链表
                    if ((e = p.next) == null) {			//如果下一个结点是空节点,说明已经到链表尾部,则插入链表尾部
                        p.next = newNode(hash, key, value, null);//尾插法,jdk1.7是头插法
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st  //如果当前的链表下标大于等于“树化阈值-1”
                            treeifyBin(tab, hash);		//树化
                        break;
                    }
                    if (e.hash == hash &&			
                        ((k = e.key) == key || (key != null && key.equals(k))))//如果链表上有与该key相等的键值对,直接break
                        break;
                    p = e;	//p = p.next,p指向想一个结点
                }
            }
            if (e != null) { // existing mapping for key,待插入的key已经存在在该map中
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null) //如果满足条件,则新的value代替旧的value
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;	//返回旧的value
            }
        }
        ++modCount;			//map结构修改次数+1
        if (++size > threshold)		//如果插入后的size大于threshold(阈值初始时=capacity*loadfactory,后面要看resize()方法里面),则重新分配桶的数量
            resize();
        afterNodeInsertion(evict);
        return null;
    }

上面就是HashMap添加元素的方法逻辑。下面来看看扩容方法

 /** //初始化桶的数量,或者将桶的数量变成2倍,如果桶的数量0,则将桶的容量设置为和capacity保持一致
     * 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.
     *
     * @return the table	//返回新的table
     */
    final Node<K,V>[] resize() {//扩容方法,该方法一般会将桶的数量扩大至原来的2倍,总之执行该方法后桶的数量应该是2的倍数
        Node<K,V>[] oldTab = table;			//将当前桶的引用赋给oldtable
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//旧的桶数量(容量)赋给oldCap
        int oldThr = threshold;				//旧的阈值赋给oldThr
        int newCap, newThr = 0;
        if (oldCap > 0) {				//若旧的容量(桶的数目)大于0
            if (oldCap >= MAXIMUM_CAPACITY) {		//若旧的桶数大于等于预先定义的最大容量
                threshold = Integer.MAX_VALUE;		//阈值等于int的最大值,然后返回旧的桶的引用,也就是说没扩容?
                return oldTab;
            }//否则newCap=oldCap*2,如果这个newCap<最大容量并且旧的容量大于等于默认的初始容量
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold //那么新的阈值等于旧的阈值的2倍。合起来就是桶数变两倍,阈值也变两倍
        }
        else if (oldThr > 0) //否则如果旧的容量=0,并且旧的阈值大于0,那么新的容量等于旧的阈值
            newCap = oldThr;
        else {               // 到这一步的条件就是旧的容量=0,旧的阈值也等于0,应该是初始化的时候
            newCap = DEFAULT_INITIAL_CAPACITY;//新容量等于默认的初始化容量,即桶的数量=16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//新的阈值等于默认加载因子*默认初始容量,即16*0.75
        }
        if (newThr == 0) {//这个条件满足意味着上面的if-else每一个满足的,其实就是从if(oldCap>0){else if((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)直接跳到这的}
            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) {	//将旧map中的元素放到新的map中
            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;
    }

其他方法还没仔细研究,以后再补补吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值