HashMap 中的容量与扩容实现,细致入微,值的一品!

2022-10-13,,,,

前言

  开心一刻  

    巴闭,你的脚怎么会有味道,我要闻闻看是不是好吃的,嗯~~爸比你的脚臭死啦!! ……

高手过招,招招致命

  jdk1.8 中 hashmap 的底层实现,我相信大家都能说上来个 一二,底层数据结构 数组 + 链表(或红黑树) ,源码如下

/**
 * 数组
 */
transient node<k,v>[] table;

/**
 * 链表结构
 */
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;
    }
}

/**
 * 红黑树结构
 */
static final class treenode<k,v> extends linkedhashmap.entry<k,v> {
    treenode<k,v> parent;  // red-black tree links
    treenode<k,v> left;
    treenode<k,v> right;
    treenode<k,v> prev;    // needed to unlink next upon deletion
    boolean red;
    ...

  但面试往往会问的比较细,例如下面的容量问题,我们能答上来几个?

    1、table 的初始化时机是什么时候,初始化的 table.length 是多少、阀值(threshold)是多少,实际能容下多少元素

    2、什么时候触发扩容,扩容之后的 table.length、阀值各是多少?

    3、table 的 length 为什么是 2 的 n 次幂

    4、求索引的时候为什么是:h&(length-1),而不是 h&length,更不是 h%length

    5、 map map = new hashmap(1000); 当我们存入多少个元素时会触发map的扩容; map map1 = new hashmap(10000); 我们存入第 10001个元素时会触发 map1 扩容吗

    6、为什么加载因子的默认值是 0.75,并且不推荐我们修改

  由于我们平时关注的少,一旦碰上这样的 连击 + 暴击,我们往往不知所措、无从应对;接下来我们看看上面的 6 个问题,是不是真的难到无法理解 ,还是我们不够细心、在自信的自我认为

斗智斗勇,见招拆招

  上述的问题,我们如何去找答案 ? 方式有很多种,用的最多的,我想应该是上网查资料、看别人的博客,但我认为最有效、准确的方式是读源码

  问题 1:table 的初始化

    hashmap 的构造方法有如下 4 种

/**
 * 构造方法 1
 *
 * 通过 指定的 initialcapacity 和 loadfactor 实例化一个空的 hashmap 对象
 */
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);
    this.loadfactor = loadfactor;
    this.threshold = tablesizefor(initialcapacity);
}

/**
 * 构造方法 2
 *
 * 通过指定的 initialcapacity 和 默认的 loadfactor(0.75) 实例化一个空的 hashmap 对象
 */
public hashmap(int initialcapacity) {
    this(initialcapacity, default_load_factor);
}

/**
 * 构造方法 3
 *
 * 通过默认的 initialcapacity 和 默认的 loadfactor(0.75) 实例化一个空的 hashmap 对象
 */
public hashmap() {
    this.loadfactor = default_load_factor; // all other fields defaulted
}

/**
 *
 * 构造方法 4
 * 通过指定的 map 对象实例化一个 hashmap 对象
 */
public hashmap(map<? extends k, ? extends v> m) {
    this.loadfactor = default_load_factor;
    putmapentries(m, false);
}

    构造方式 4 和 构造方式 1 实际应用的不多,构造方式 2 直接调用的 1(底层实现完全一致),构造方式 2 和 构造方式 3 比较常用,而最常用的是构造方式 3;此时我们以构造方式 3 为前提来分析,而构造方式 2 我们则在问题 5 中来分析

     使用方式 1 实例化 hashmap 的时候,table 并未进行初始化,那 table 是何时进行初始化的了 ? 平时我们是如何使用 hashmap 的,先实例化、然后 put、然后进行其他操作,如下

map<string,object> map = new hashmap();
map.put("name", "张三");
map.put("age", 21);

// 后续操作
...

    既然实例化的时候未进行 table 的初始化,那是不是在 put 的时候初始化的了,我们来确认下

      resize() 初始化 table 或 对 table 进行双倍扩容,源码如下(注意看注释)

/**
 * 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;                    // 第一次 put 的时候,table = null
    int oldcap = (oldtab == null) ? 0 : oldtab.length; // oldcap = 0
    int oldthr = threshold;                        // threshold=0, oldthr = 0
    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;    // default_initial_capacity = 1 << 4 = 16, newcap = 16;
        newthr = (int)(default_load_factor * default_initial_capacity);    // newthr = 0.75 * 16 = 12;
    }
    if (newthr == 0) {    // 条件不满足
        float ft = (float)newcap * loadfactor;
        newthr = (newcap < maximum_capacity && ft < (float)maximum_capacity ?
                  (int)ft : integer.max_value);
    }
    threshold = newthr;        // threshold = 12; 重置阀值为12
    @suppresswarnings({"rawtypes","unchecked"})
        node<k,v>[] newtab = (node<k,v>[])new node[newcap];     // 初始化 newtab, length = 16;
    table = newtab;            // table 初始化完成, length = 16;
    if (oldtab != null) {    // 此时条件不满足,后续扩容的时候,走此if分支 将数组元素复制到新数组
        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;    // 新数组
}

     自此,问题 1 的答案就明了了

table 的初始化时机是什么时候
    一般情况下,在第一次 put 的时候,调用 resize 方法进行 table 的初始化
    
初始化的 table.length 是多少、阀值(threshold)是多少,实际能容下多少元素
    默认情况下,table.length = 16; 指定了 initialcapacity 的情况放到问题 5 中分析
    默认情况下,threshold = 12; 指定了 initialcapacity 的情况放到问题 5 中分析
    默认情况下,能存放 12 个元素,当存放第 13 个元素后进行扩容

  问题 2 :table 的扩容

     putval 源码如下

/**
 * 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;
    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)             // 当size(已存放元素个数) > thrshold(阀值),进行扩容
        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;                    // 此时的 table != null,oldtab 指向旧的 table
    int oldcap = (oldtab == null) ? 0 : oldtab.length; // oldcap = table.length; 第一次扩容时是 16
    int oldthr = threshold;                        // threshold=12, oldthr = 12;
    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左移一位; newcap = 16 << 1 = 32;
                 oldcap >= default_initial_capacity)
            newthr = oldthr << 1; // double threshold            // newthr = 12 << 1 = 24;
    }
    else if (oldthr > 0) // initial capacity was placed in threshold
        newcap = oldthr;
    else {               // zero initial threshold signifies using defaults
        newcap = default_initial_capacity;    // default_initial_capacity = 1 << 4 = 16, newcap = 16;
        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;        // threshold = newthr = 24; 重置阀值为 24
    @suppresswarnings({"rawtypes","unchecked"})
        node<k,v>[] newtab = (node<k,v>[])new node[newcap];     // 初始化 newtab, length = 32;
    table = newtab;            // table 指向 newtab, length = 32;
    if (oldtab != null) {    // 扩容后,将 oldtab(旧table) 中的元素移到 newtab(新table)中
        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;
}

    自此,问题 2 的答案也就清晰了

什么时候触发扩容,扩容之后的 table.length、阀值各是多少
    当 size > threshold 的时候进行扩容
    扩容之后的 table.length = 旧 table.length * 2,
    扩容之后的 threshold = 旧 threshold * 2

  问题 3、4 :2 的 n 次幂

    table 是一个数组,那么如何最快的将元素 e 放入数组 ? 当然是找到元素 e 在 table 中对应的位置 index ,然后 table[index] = e; 就好了;如何找到 e 在 table 中的位置了 ? 我们知道只能通过数组下标(索引)操作数组,而数组的下标类型又是  int ,如果 e 是 int 类型,那好说,就直接用 e 来做数组下标(若 e > table.length,则可以 e % table.length 来获取下标),可  key - value 中的 key 类型不一定,所以我们需要一种统一的方式将 key 转换成  int ,最好是一个  key 对应一个唯一的 int (目前还不可能, int有范围限制,对转换方法要求也极高),所以引入了 hash 方法

static final int hash(object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashcode()) ^ (h >>> 16);  // 这里的处理,有兴趣的可以琢磨下;能够减少碰撞
}

    实现 key 到 int 的转换(关于 hash,本文不展开讨论)。拿到了 key 对应的 int h 之后,我们最容易想到的对 value 的  put 和 get 操作也许如下

// put
table[h % table.length] = value;

// get
e = table[h % table.length];

    直接取模是我们最容易想到的获取下标的方法,但是最高效的方法吗 ?

    我们知道计算机中的四则运算最终都会转换成二进制的位运算

    我们可以发现,只有 & 数是1时,& 运算的结果与被 & 数一致

1&1=1;
0&1=0;
1&0=0;
0&0=0;

    这同样适用于多位操作数

1010&1111=1010;      => 10&15=10;
1011&1111=1011;      => 11&15=11;
01010&10000=00000;   => 10&16=0;
01011&10000=00000;   => 11&16=0;

    我们是不是又有所发现: 10 & 16 与 11 & 16 得到的结果一样,也就是冲突(碰撞)了,那么 10 和 11 对应的 value 会在同一个链表中,而 table 的有些位置则永远不会有元素,这就导致 table 的空间未得到充分利用,同时还降低了 put 和 get 的效率(对比数组和链表);由于是 2 个数进行 & 运算,所以结果由这两个数决定,如果我们把这两个数都做下限制,那得到的结果是不是可控制在我们想要的范围内了 ?  我们需要利用好 & 运算的特点,当右边的数的低位二进制是连续的 1 ,且左边是一个均匀的数(需要 hash 方法实现,尽量保证 key 的 h 唯一),那么得到的结果就比较完美了。低位二进制连续的 1,我们很容易想到 2^n - 1; 而关于左边均匀的数,则通过 hash 方法来实现,这里不做细究了。

    自此,2 的 n 次幂的相关问题就清楚了

table 的 length 为什么是 2 的 n 次幂
    为了利用位运算 & 求 key 的下标

求索引的时候为什么是:h&(length-1),而不是 h&length,更不是 h%length
    h%length 效率不如位运算快
    h&length 会导致 table 的空间得不到利用、降低 table 的操作效率

    给各位留个疑问:为什么不直接用 2^n-1 作为 table.length ? 欢迎评论区留言

  问题 5:指定 initialcapacity

    当我们指定了 initialcapacity,hashmap的构造方法有些许不同,如下所示 

    调用 tablesizefor 进行 threshold 的初始化

/**
 * returns a power of two size for the given target capacity.
 * 返回 >= cap 最小的 2^n
 * cap = 10, 则返回 2^4 = 16;
 * cap = 5, 则返回 2^3 = 8;
 */
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;
}

    虽然此处初始化的是 threshold,但后面初始化 table 的时候,会将其用于 table 的 length,同时会重置 threshold 为 table.length * loadfactor 

    自此,问题 5 也就清楚了

map map = new hashmap(1000); 当我们存入多少个元素时会触发map的扩容
    此时的 table.length = 2^10 = 1024; threshold = 1024 * 0.75 = 768; 所以存入第 769 个元素时进行扩容

map map1 = new hashmap(10000); 我们存入第 10001个元素时会触发 map1 扩容吗
    此时的 table.length = 2^14 = 16384; threshold = 16384 * 0.75 = 12288; 所以存入第 10001 个元素时不会进行扩容

  问题6:加载因子

为什么加载因子的默认值是 0.75,并且不推荐我们修改
    如果loadfactor太小,那么map中的table需要不断的扩容,扩容是个耗时的过程
    如果loadfactor太大,那么map中table放满了也不不会扩容,导致冲突越来越多,解决冲突而起的链表越来越长,效率越来越低
    而 0.75 这是一个折中的值,是一个比较理想的值

总结

  1、table.length = 2^n,是为了能利用位运算(&)来求 key 的下标,而 h&(length-1) 是为了充分利用 table 的空间,并减少 key 的碰撞

  2、加载因子太小, table 需要不断的扩容,影响 put 效率;太大会导致碰撞越来越多,链表越来越长(转红黑树),影响效率;0.75 是一个比较理想的中间值

  3、table.length = 2^n、hash 方法获取 key 的 h、加载因子 0.75、数组 + 链表(或红黑树),一环扣一环,保证了 key 在 table 中的均匀分配,充分利用了空间,也保证了操作效率

    环环相扣的,而不是心血来潮的随意处理;缺了一环,其他的环就无意义了!

  4、网上有个 put 方法的流程图画的挺好,我就偷懒了

参考

   java提高篇(二三)-----hashmap
  【原创】hashmap复习精讲
  面试官:"准备用hashmap存1w条数据,构造时传10000还会触发扩容吗?"

《HashMap 中的容量与扩容实现,细致入微,值的一品!.doc》

下载本文的Word格式文档,以方便收藏与打印。