【源码解析】深入理解HashMap

一、静态区域

6参数:static final

6参数,初始化的大小以及最终的限定范围,其余四个和树化有关,一个是threshold相关的参数,其余的是判定是否能够树化以及树的退化的条件

// 初始化HashMap的时候,如果没有赋值,那么我们会给它赋上默认的缺省值为16
//数组一开始的大小默认就为16,即HashMap中桶的数量 2^4     【凡涉及到"容量"一词,都是指桶的数量】
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

// 扩容之后最大的数组容量为2^30(非元素个数)
static final int MAXIMUM_CAPACITY = 1 << 30;

/**【计算扩容阈值参数】
* 负载因子,用来计算下一次的阈值使用,在初始化的时候会使用到
* 构造方法中,或者是put元素的时候还未初始化hashMap,进入到resize方法中调用该参数。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**【树化阈值】
* (1)链长达8
* 		在putVal方法中,如果当前桶中的元素形成的链的长度超过该值,默认8那么就是到了9之后会树化
* 		为了保证hashMap的查找效率,避免莲花长度太长导致的效率低下而设置的值
* (2)数组的长度达到64
* 		treeifyBin方法使用到,至少为树化链长的4倍
*/
static final int TREEIFY_THRESHOLD = 8;
static final int MIN_TREEIFY_CAPACITY = 64;

/**【退化阈值】
* 在split中会使用到该缺省值,用于树的退化,树的退化阈值为6,
* 	当前树的结点小于6就没有必要继续维持树的状态了
*/
static final int UNTREEIFY_THRESHOLD = 6;

Node结构(HashMap)

定义了hashmap中的每个参数都有hash值(int类型的为了平均散列高位参与运算使用hash扰动函数),key、val、以及下一个元素的位置(链化前为null)

优化哈希算法:
hash ^ (hash >>> 16)
无符号右移16位,扰动函数使得哈希值二次散列,使得低位的值也能加入计算

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
	
	//构造方法
    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            //key和val都相等的时候,返回true
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

二、base:基础函数

成员变量:

	transient Node<K,V>[] table;
	transient Set<Map.Entry<K,V>> entrySet;
	
// HashMap中所有元素的个数,K-V对数
	transient int size;
// 下次resize(扩容)的操作的size值。
	int threshold;
	
//HashMap结构改变的次数
	transient int modCount;
//loadFactor是定义好的
    final float loadFactor;

在这里插入图片描述

HashMap(int, float) 构造函数:

说明了可以给定的值为 初始的数组大小负载因子

public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
	//处理完异常的情况就可以赋值loadFactor 和threshold 了
	//	但是此时我们还没有创建出来真正的HashMap,为了优化,我们延迟了初始化
	//	后续我们在resize中会对HashMap进行初始化(创造结构)
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR); //简洁!套娃
}
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

hash( ) 扰动函数

在这里插入图片描述

一、如果没有(h >>> 16)的话,会使得元素不够散列,使得高位的hash结果损失,
有这个也是为了将高位的特征保留到低位中,将高低位二进制特征混合起来综合判断
二、在后续的 hash & ( n -1 )时,如果只有17个桶,那么我们必然收集不到原本足够散列的高位特征,必然导致最终的结果有一定的数据偏移

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

取二的幂次数:tableSizeFor( )

使得输入的参数向上转移为2的幂次方

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

树化节点:treeifyBin

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 进来之前已经保证了链长>8,这里判断是否达到最小树化阈值64。
        // tab为空:初始化;n < 最小树化阈值
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

三、public:公开函数

getNode( ) 获取元素

get逻辑:通过getNode =》拿到key的判断结果==》Node e =》拿到e.value返回

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

get方法里面直接套娃getNode,获取Node方法,给key就足够了

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    //如果现在的表非空,且有长度,first指向表中的指定index桶[(n-1)&hash]
    //与此同时,tab、n、first设定值,只要一个不满足,return null
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        //1、first就是的key相同,return first
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        //2、first不是,继续找下一个【排除首个元素的情况】
        if ((e = first.next) != null) {
        	//如果first是树,那么在树里面找Node
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            //否则e作为临时元素不断向下寻找,直到key相同(hash之后相同 and key地址相同或者值相同)
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
            //到这里如果还是没有值,那说明不是单个元素,也不是树里面的,也不是链表中的值
            // ==》 没有需要的值 ==》 返回 null
        }
    }
    return null;
}

赠品:

通过getNode来判断是否存在元素

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

⭐put( )

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

正常的插入方法:
1、桶里面没有元素,直接放入(k, v, next)
2、桶里面是个链表,循环到最后加进去(判断是否可以树化,超过阈值)
3、桶是一个树,插入树的方法,调用树的插入

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //赋初值,判断是否初始化完成,没有的话进入resize中newThr、newCap赋值
    //tab、n
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    
    //1、对应的桶没有元素,那么直接放入table[index],p指向table[index]
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        //第一位里面有值,将e赋值p作为临时节点,【替换】
        //e用来装载旧的值,如果进去了直接到最后直接将e节点的值赋值为新值就ok【e用作替换的临时元素使用】
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //p是树:
        //1、返回的e为空说明是子树,不参与替换
        //2、是中间的树,那么替换
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        //链表情况:
        else {
        	//只要p.next有值,就一直判断key的值有没有一样的,一样的就break,说明找到了要替换的节点
        	//如果在找的时候已经到了终点,直接创建新的 node,如果达到阈值,那么对tab树化,此时e为null,不要替换
            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
                    	//treefiy只对当前的桶树化。
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //e不为空,那说明有替换的元素,只需要将value的值赋值给需要替换的元素上就ok
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    //结构改变++
    ++modCount;
    //键值对的数量达到阈值,对tab进行扩容操作。
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

流程图如下:
思维导图

⭐resize()

1、扩容:根据当前大小赋值
2、初始化

final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    
    //newCap, newThr为新的结构进行初始化
    int newCap, newThr = 0;
    if (oldCap > 0) {
		//put过的tab,旧容量已经超过所能承受的2^30,那就只能随便碰撞了
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //没超过:newThr、newCap 二者都扩容
        //满足:newCap = oldCap * 2 不超 and oldCap大于默认initial容量,直达最后new环节
        //不满足:Cap为两倍,但是newThr为0.根据newCap设置大小为newCap * loadFactor。
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1; // double threshold
    }
    //cap=0,oldThr > 0:阈值里面保存的就是新的容量大小,但是还没有给newThr赋值,后面还会对它进行赋值
    else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
    //cap=0,oldThr=0:将新的设置为默认的容量和默认的阈值
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    //newThr未定义,重新定义newThr,定义resize上限
    if (newThr == 0) {
     	//不能超过阈值,否则直接把Thr阈值设置为最大值,永远不让你扩容resize
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    
    //根据newThr和newCap来 init 新的table
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    
    //oldTab里面有东西:搬运到新的tab中
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
            	//释放oldTab空间
                oldTab[j] = null;
                //达到oldTab最后一个位置,直接拼接到最后的位置
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                //属于数的情况,将树退化
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                //设高位和低位,oldCap:100000,当前元素最高位为0,放到低位的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;
                        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;
                    }
                    //高hash值的链表放入数组的原始位置 + 原始容量
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    //扩容完成,返回newTab
    return newTab;
}

总结这个最好是分为两个图比较清晰,第一个是给newThr和newTab赋值;第二个是给元素搬家的操作。(以注解 @SuppressWarnings({"rawtypes","unchecked"})为分界)

第一部分:
在这里插入图片描述
第二部分:
得到了newCap和newThr
newCap还是空空如也,只是知道要搬的新家有多大。
得到table和threshold

在这里插入图片描述

remove( )

又一个套娃方法,这个方法也是我们最常用的方法:不需要matchValue就可以remove元素的方法

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    // init tab、n、p、index
    if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
    	// 下面的逻辑非常清晰,就是使用node装载需要remove的元素
    	// 首先要找到node,然后交给下一个循环处理node
        Node<K,V> node = null, e; K k; V v;
        // 1、单个元素,首个元素
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            // 2、节点为树
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            // 3、节点为链表,但是也有可能找不到对应的元素
            else {
                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        // 得到node为要删除的对象,分情况对node进行处理,有这一步主要还是有需要value和key都对上才删除的情况
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

remove方法的解析

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

willorn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值