Hashmap底层源码

仅个人理解如有不对,欢迎指正,初学者

以下内容都是源码粘贴,有些顺序混乱,自己查看hashmap源码对照着看,排版混乱见谅

hashset底层是一个hashmap 
private static final Object PRESENT = new Object();//PRESENT其实就是占位符,没啥用
public boolean add(E e) {//1️⃣一个泛型的e,传的是字符串常量("我们传的值")
        return map.put(e, PRESENT)==null;//PRESENT,不管key怎么变换,vaue始终为PRESENT,大家共享的,🔟返回为空添加成功,不返回空表示添加失败
    }

public V put(K key, V value) {//2️⃣执行put方法,key是我们的字符串常量("我们传的值"),value为1️⃣的PRESENT,执行hashkey方法,得key对应哈希值,不等价于hashcode
        return putVal(hash(key), key, value, false, true);
    }

static final int hash(Object key) {//2️⃣中的hash()方法,求得是key的hashcode值,按位抑或,无符号右移动16位,目的是为了node的存放分布更加均匀
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {//hash 1556946703 key ("我们传的值") value object@491 onlyIfAbsent false  evict true
        Node<K,V>[] tab; Node<K,V> p; int n, i;//定义辅助变量,table是hashmap的一个字段值,放Node节点的数组
        if ((tab = table) == null || (n = tab.length) == 0)//3️⃣一开始为空或者长度为〇,执行resize
            n = (tab = resize()).length;//6️⃣执行完后tab为长度16的newTab
        if ((p = tab[i = (n - 1) & hash]) == null)//7️⃣根据传入的key得到的哈希值去计算应该存放到table表的哪个索引位置,并且把这个对象的位置赋给变量p,如果p不等于空,为空就创建Node直接存
            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))))//看看p指向的node节点和准备添加的key的hash值一样,并且key就是当前的node节点的key或者key不等于空,不是同一个对象,内容相同,就不能加入
                e = p;
            else if (p instanceof TreeNode)//在判断p是不是一棵红黑树
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//如果是一颗红黑树就调用putTreeval添加
            else {//如果当前table对应的索引的位置,已经是一个链表了,就使用for循环比较
                //1)依次和该链表的每一个元素比较后都不相同,加到最后

                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);//链表往下挂
                        if (binCount >= TREEIFY_THRESHOLD(8) - 1) // -1 for 1st如果大于八对当前这个链表变成红黑树(在进行树化时还进行一个判断,如果数组大小小于MIN_TREEIFY_CAPACITY(64),只进行(表的扩容)数组的扩容)如果大于64才进行树化,
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;//如果都相等就说明都相同,直接break
                    p = e;//指向e
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;//如果不成功返回oldvalue
            }
        }
        ++modCount;//8️⃣+1修改一次就加一
        if (++size > threshold)//看看现在的大小是否超过12,如果大于12执行resize扩容
            resize();
        afterNodeInsertion(evict);//hashmap留给他的子类来实现的,这个方法目前是个空方法
        return null;//存放成功了
    }

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;//把数组传给一个oldtab
        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
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
          // ④把hashset的初始容量给newCap为16,
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//5️⃣加载因子0.75f乘以16得12,这是一个临界值,作用是到12就扩容而不是16(解决多线程并发卡住的问题)
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;//12就扩容,临界值
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//新建一个newtab为16的Node数组
        table = newTab;//把newtab给table为16
        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;
                            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;//最终返回newTab
    }

总结1️⃣先获取元素的哈希值(hashcode方法)
2️⃣对哈希值进行计算(hash得到的数为哈希值异或无符号偏移16位),得出一个索引值,即为要存放在哈希表的位置号
3️⃣如果该索引上没有其他元素,直接存入,如果有其他元素则需要调用equals判断,先判断哈希值,在比较内容
如果一样则放弃添加,如果不同则添加到链表的尾端(p.next)
4️⃣java8中如果一个链表的元素达到8并且数组大大于MIN_TREEIFY_CAPACITY(64)才进行树化,否则只是单纯的扩充数组大小

//树化扩容机制分析
final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        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);
        }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值