HashMap原理解析,以及1.8的变化

名词

1.加载因子(Load Factor):默认0.75,用于设置扩容的阈值。
2.阈值(Threshold):默认12,扩容的临界值,超过该值则进行扩容操作。
3.容量(Capacity):默认16,指HashMap内部维护的数组大小。

插值流程

主要使用put方法进行的插入。在1.8之后HashMap使用了链表加红黑树的结构来解决hash碰撞问题(hash碰撞就是指两个不同key的hash相同)。

    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;
    }

这是整个put方法的源码,我们从头开始分析。

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

当table为空或者长度为0时直接resize初始化HashMap,具体resize的逻辑后面再讲。

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

此处是指插入对象的hash指针在tab数组里还未插入过数据。直接构造链表结构插入(该链表为单链表)。
以下为出现hash碰撞的场景,也是较为复杂的部分

else {
            Node<K,V> e; K k; // e这个值用于存找到的需要替换val的目标node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;	// 此处即为头结点即为需要替换的场景
            else if (p instanceof TreeNode)	// 此处为当前hash槽为红黑树的场景,直接插入
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); 
            else {	// 此处为hash槽为链表的场景
                for (int binCount = 0; ; ++binCount) {	// 从头开始遍历链表
                    if ((e = p.next) == null) { 
                        p.next = newNode(hash, key, value, null);	// 未找到匹配的key,使用尾插法插入
                        if (binCount >= TREEIFY_THRESHOLD - 1)	// 插入后链表长度超过8就改为红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;	// 链表中找到与当前key相同的值后退出循环
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e); // link用于排序
                return oldValue;
            }
        }
		++modCount;	// 该字段用于统计map修改次数,用于在遍历的时候如果有修改抛错。
        if (++size > threshold)
            resize();	// 超限扩容
        afterNodeInsertion(evict);
        return null;

扩容流程

当前容量不为空的时候扩容两倍或设置为最大容量

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);
        }

以上都是在对新容量以及新阈值进行设置,以下代码为扩容核心代码

		threshold = newThr;
        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;
                            //这个地方很巧秒,通过e.hash & oldCap来得出newTab中的位置,
                            //因为table是2倍扩容,所以只需要看hash值与oldCap进行操作,结果为0,那么还是原来的index;否则index = index + oldCap 
                            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);
                        //即e.hash & oldCap == 0的链表索, 引不会发生变化, 直接放入newTable中 原索引 位置
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        
                        //即e.hash & oldCap != 0的链表, 索引会发生变化, 在原索引 + oldCap位置, 放到newTable中
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值