hashMap源码个人解读

本文深入探讨HashMap在Java 1.8中的实现,包括槽位算法的原理,为何容量必须为2的倍数以确保均匀分布,以及put方法和resize方法的具体解析。在resize过程中,HashMap通过拆分链表并重新计算键值在扩容后的槽位,而不是重新计算所有键的哈希值,从而提高效率。
摘要由CSDN通过智能技术生成

使用的jdk是1.8

在看源码前,你需要看下hashmap的数据结构的图,这样能帮助你理解分析源码:

关于hashmap槽位算法(数组下标)的思考(也叫为什么hashmap的容量为什么是2的倍速):

其实在1.8的源码里可以看见计算槽位的公式很简单: (n - 1) & hash 此公式可以理解为 hash % ( n-1)计算除以长度得到的下标即是数组下标了. 不过是用位运算效率高,所以采用这种方式

为什么要求n是2的倍数呢?我当时也很好奇,知道后来看到几篇博客,理解到了其中的原由. 2的倍数减1的二进制位后面都是111111 比如15的2进制是0000 1111, 如果某个key的hash是0000 1100 那么两者与运算的结果是

n-1 0000 1111

hash 0000 1100

结果: 0000 1100

你会发现这结果是由hash决定的, 如果hash是散列的, 那么计算出来的槽位下标也是分散的.

put方法解析

介绍一下hashmap的put方法,从hashmap的源码复制出来的

/**
 * Implements Map.put and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    // 
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // transient Node<K,V>[] table;初始化
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // (n - 1) & hash 计算数组下标的方法快看腻了, 很多博客都写出来
    //如果计算到下标的槽没有值(即没有发生哈希冲突),那就直接new Node放到当前槽位
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    // 如果进入这个else 就是发生哈希冲突
    else {
        Node<K,V> e; K k;
        // 计算哈希冲突的处理方法1
        // 当前槽位的链表的第一个元素(下面用p表示)和待input的node的hash是否一致,key是否一致,如果一致(即插入相同的key),跳转到47行 的 if (e != null){覆盖操作,或者不覆盖操作}
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 跳过了上面的if,则开始便利当前槽位的链表,检查是否含有与待input的node一样的node,如果没有则在尾部插入,如果有则 跳转到53行 的 if (e != null){覆盖操作,或者不覆盖操作}
        // 遍历的方式有2种,一种链表的方式遍历,一种红黑树的方式遍历
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        // 链表的方式遍历
        else {
            for (int binCount = 0; ; ++binCount) {
                // 当前槽位的链表遍历到最后一个元素,如果发现没有与待input的node一样,使用尾插法进行插入
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 这里的话,看binCount的值是否 >= 7 是则使用转换链表为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                // 检查当前node是否和待input的node一样的key,则循环结束跳转到53行的if (e != null){覆盖操作,或者不覆盖操作}
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 如果 e != null则代表map中含有与待input node一样的key的node,看输入的onlyIfAbsent的值决定是否覆盖
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            // 这里是给linkedhashmap用的,每次get或者put都调整链表的顺序,以实现LRU,不过在hashmap里,这个afterNodeAccess()是什么都没有的
            afterNodeAccess(e);
            return oldValue;
        }
    }
    // modCount是标记操作当前map的的动作的个数
    ++modCount;
    // 判断map扩容 ,如果找过阈值则扩容,比如阈值默认是16,你超过16个则扩容. 和1.7的有挺大区别,1.7的扩容时机可以后面我参考的博客
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
resize方法解析
/**
 * 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
 */
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 >= 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);
    }
    if (newThr == 0) {
        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) {
        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;
}

主要讲关于链表的扩容方式

其实下面的源码没什么特别的地方,最前面是一些边界值的检查, 后面开始扩容, 但是没有我们想象中的那样从头到叫hash计算一遍然后放进新的map中.

看了其他大佬对1.8的扩容算法的解析后,我懂了这个大概方法是怎么回事.这里的扩容不会重新再来计算一次hash,费事,而是将每个槽位的链表进行拆分为2个链表, 使用e.hash && oldCap重新计算该key在扩容后是否还在原来的位置,如果计算的结果是0 则是在原来是位置, 否则肯定计算到的槽位是原来的槽位 * 2 ,因为hashmap是2倍扩容的.

所以上面的源码是拆分成2个队列,一个是在原来槽位的位置,一个是在index+oldCap中.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值