HashMap源码学习,,小白晋级之路

HashMap源码学习 及 问题

提前须知

1.文本中注解后的文字中出现的 ^ 不代表异或 ,表示该数的次幂

2.oldCap 旧的map容量 oldThr 旧的map实际使用容量 newCap 扩容后的map容量 newThr 扩容后的实际使用容量

  1. loadFactor 负载工厂 在hashmap的构造函数中设置为0.75
/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
 public HashMap() {
     this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
 }

4.Node<K,V>为hashmap中创建的静态内部类 , 实现Map.Entry<K,V>

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;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

5.HashMap中put执行13次进行一次扩容 , ConcurrentHashMap中put12次进行一次扩容

put方法

先执行put方法 , 调用put内部的putval方法

put{
    putVal(hash(key), key, value, false, true);
}

首先判断Node<K,V>是否为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)
            n = (tab = resize()).length; //容量初始化处
    
        ........ //暂时省略
            
        if (++size > threshold)
            resize();   //扩容处
        afterNodeInsertion(evict);
        return null;
    }

如果Node<K,V>是null , 进入resize()方法初始化容量

resize(){
	Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) { //hashmap扩容具体实现
           .............. //暂略 , 在下面详细说明
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr; 
        else {               // 初始化hashmap容量实现部分
            newCap = DEFAULT_INITIAL_CAPACITY; //默认初始化容量 16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //实际可使用的容量
            //默认的负载因子 * 默认初始化容量 = 16 * 0.75 = 12
        }
 //此处暂时有疑问
        if (newThr == 0) { // 如果使用容量为0
            float ft = (float)newCap * loadFactor; //tab容量 * 0.75
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr; //将实际使用容量赋值给threshold变量
        @SuppressWarnings({"rawtypes","unchecked"})
        //将得到的newCap赋给节点数组
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; 
        table = newTab;
        if (oldTab != null) {
           ........//暂略 , 初始化容器不考虑此部分
        }
        return newTab;
}

如果Node<K,V>不为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 > 0) { //hashmap扩容具体实现
            if (oldCap >= MAXIMUM_CAPACITY) { //判断node长度是否大于hashmap最大长度 1>>30 即 2^30
                threshold = Integer.MAX_VALUE;
                return oldTab; //MAXIMUM_CAPACITY 即 HashMap中最大长度,达到这个标准后不再扩容
            }
            //当map容量扩大1倍,即*2后小于最大容量2^30 同时 map容量大于等于默认初始容量(DEFAULT_INITIAL_CAPACITY = 1 << 4)
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY) 
                newThr = oldThr << 1; // double threshold 容量扩大1倍
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // 初始化容器
           .......   //暂略
        }
         //此处暂时有疑问
        if (newThr == 0) { // 如果使用容量为0
            float ft = (float)newCap * loadFactor; //tab容量 * 0.75
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
       		threshold = newThr; //将实际使用容量赋值给threshold变量
        @SuppressWarnings({"rawtypes","unchecked"})
        //将得到的newCap赋给节点数组
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; 
        table = newTab;
        if (oldTab != null) { //node数组扩容后 , 对于node的重新分配
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null; //将当前节点置为null
                    if (e.next == null) //node不存在链表和红黑树
                        newTab[e.hash & (newCap - 1)] = e; // 在一个新的位置存储oldNode
                        //将原节点的hash值(存储节点时同步储存的hash值) & newCap-1 (算法暂不深究)
                        //(个人理解)用& ! | 进行二进制计算会提高效率
                    else if (e instanceof TreeNode) // node存在红黑树
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // node 存在链表
                        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;
    }

TreeNode<K,V>中的split解释

final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
        TreeNode<K,V> b = this;                     //传递的 e ,即 Node[j]
        // Relink into lo and hi lists, preserving order
        TreeNode<K,V> loHead = null, loTail = null; //低位头和低位尾 即 lowerHead lowerTail
        TreeNode<K,V> hiHead = null, hiTail = null; //高位头和高位尾 即hightHead hightTail
        int lc = 0, hc = 0;
        for (TreeNode<K,V> e = b, next; e != null; e = next) {
            next = (TreeNode<K,V>)e.next;
            e.next = null;
            if ((e.hash & bit) == 0) { //node.hash值 & oldCap == 0
                if ((e.prev = loTail) == null) //在低位储存
                    loHead = e;
                else
                    loTail.next = e;
                loTail = e;
                ++lc;
            }
            else { //在高位储存
                if ((e.prev = hiTail) == null)
                    hiHead = e;
                else
                    hiTail.next = e;
                hiTail = e;
                ++hc;
            }
        }

        if (loHead != null) {
            if (lc <= UNTREEIFY_THRESHOLD) //如果长度小于6 则将该节点转换为链表结构
                tab[index] = loHead.untreeify(map);//调用untreeify方法,在下面详解
            else {
                tab[index] = loHead;
                if (hiHead != null) // (else is already treeified)
                    loHead.treeify(tab);
            }
        }
        if (hiHead != null) {
            if (hc <= UNTREEIFY_THRESHOLD)
                tab[index + bit] = hiHead.untreeify(map);
            else {
                tab[index + bit] = hiHead;
                if (loHead != null)
                    hiHead.treeify(tab);
            }
        }
    }

TreeNode<K,V>中的untreeify方法

final Node<K,V> untreeify(HashMap<K,V> map) {
            Node<K,V> hd = null, tl = null;
            for (Node<K,V> q = this; q != null; q = q.next) {
                Node<K,V> p = map.replacementNode(q, null); //此方法为替换节点,即按照对应的hash值创建一个新节点 -------> return new Node<>(p.hash, p.key, p.value, next); 
                //相同的hash值,依次进行next存值
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

回到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;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)  //与之匹配的hash槽为null 则创建一个新的节点放到里面
            tab[i] = newNode(hash, key, value, null);
        else { //不为null
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) //key相同,值替换
                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) // 判断链表长度 >=7 则转换为红黑是
                            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;
    }
get方法,相对简单许多
public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value; //调用getNode()方法
    }

getNode()方法

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) { //找到对应的hash槽 ,判断其不为空
            if (first.hash == hash && //当对应hash槽中只有一个节点 , 即不存在链表和红黑树
                ((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);
                do {// 属于链表 .next查找
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
DEFAULT_LOAD_FACTOR 默认负载因子只在初始化容器是使用一次 , 之后不再使用 , 扩容只将现有的oldThr << 1

知识点

1.transient修饰的变量不能被序列化
	1)什么时候需要使用序列化
		a)当你想把的内存中的对象保存到一个文件中或者数据库中时候;
		b)当你想用套接字在网络上传送对象的时候;
		c)当你想通过RMI传输对象的时候;
2.计算二进制数直接用电脑自带的计算器转换即可
	其中1<<n 表示 2^n次方
	左移一位 , 数字大一倍
	右移一位 , 数字小一倍
	二进制表遵循左高右低
3.hashmap中链表,红黑树中的节点的位置比较使用的都是判断node.hash & oldCap是否等于0
4.jdk1.8中的hash算法的变化
	 (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
5.判断新增的数据存放的位置
	使用(oldCap - 1) & hash 得出新增的数据该放在哪个hash槽中
	其中(oldCap - 1) & hash 效率会很高,获取的即是hashmap中hash槽的位置

存在的问题

split中高位存值,和低位存值,为什么进行两次判断 , 判断完高位的数量 , 又判断低位的数量

红黑树的存储算法

下面的(3)存在的意义

if ((e.hash & oldCap) == 0) {
	if (loTail == null)
		loHead = e;
	else
		loTail.next = e;
	loTail = e; (3)
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值