HashMap 面试常见的6连问,你能扛得住吗?

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
}

/**

* 红黑树结构

*/

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;

f0f8c04fadb3232519aaa2d65c6c95d9.png

图片

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

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 的时候初始化的了,我们来确认下

ef5de77244acb35b203582aed2a7486a.gif

图片

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

最后

2020年在匆匆忙忙慌慌乱乱中就这么度过了,我们迎来了新一年,互联网的发展如此之快,技术日新月异,更新迭代成为了这个时代的代名词,坚持下来的技术体系会越来越健壮,JVM作为如今是跳槽大厂必备的技能,如果你还没掌握,更别提之后更新的新技术了。

更多JVM面试整理:

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!
将 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];

最后

2020年在匆匆忙忙慌慌乱乱中就这么度过了,我们迎来了新一年,互联网的发展如此之快,技术日新月异,更新迭代成为了这个时代的代名词,坚持下来的技术体系会越来越健壮,JVM作为如今是跳槽大厂必备的技能,如果你还没掌握,更别提之后更新的新技术了。

[外链图片转存中…(img-YFtOFgNk-1714642890767)]

更多JVM面试整理:

[外链图片转存中…(img-pxYhXlRH-1714642890768)]

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

  • 19
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值