面试过程中经常会被问到是否了解过hashmap的底层原理。
下面咱们直接看点,下面解释为个人理解,如有不错误的地方请大家及时指出。
/**
* 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() {
//把旧的table 赋值个一个变量
Node<K,V>[] oldTab = table;
//获取旧的tabel的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 旧的阈值
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//判断数组的长度是否大约等于最大值
if (oldCap >= MAXIMUM_CAPACITY) {
//如果数组的长度达到了最大值,那么就不在进行扩容,直接返回,不管了任由hash冲突
threshold = Integer.MAX_VALUE;
return oldTab;
//把旧的数组长度左移一位(也就是乘以2),然后判断是否小于最大值,并且判断旧的数组长度是否大于等于默认的长度16
}else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//如果条件成立就把旧的阈值左移一位复制给新的阈值
newThr = oldThr << 1; // double threshold
}//如果就的数组长度小于0并且旧的阈值大于0
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);
}
//如果新的阈值等于0
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;
//如果没有子元素那么说明是下面不是一个链表,直接通过 hash&(新的数组长度-1)计算出新的位置,把就的数据放入新的位置
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
//有多个数据并且不是树那么该节点上放的是链表
//这里是java1.8很精妙的地方,如果 e.hash& 旧的数组长度 如果等于0
那么该数据的位置没有发生变化,还在原来的索引位置上,如果不等于0 那么就在该值就在 (原来的索引位置+旧的数组长度)的位置上,
这里重新创建了两个节点,在原来位置上的放入loHead中,在新的位置上的放入
hiHead 中,最后把这两组数据放入新的数组中即可。(这里的精妙之处是不用重新计算每一个数据的hash,就可以把旧的数据放入新的数组中去)
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;
}
具体的解释已经在代码上做了注释,这样方便查看,下面是代码中用的常量
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
//数组的最大长度
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The default initial capacity - MUST be a power of two.
*/
//数组的默认初始长度,java规定hashMap的数组长度必须是2的次方
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The load factor used when none specified in constructor.
*/
//默认负载因子,当元素个数超过这个比例则会执行数组扩充操作
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The load factor for the hash table.
*
* @serial
*/
//哈希表的加载因子 该值会在hashmap的构造函数中去进行赋值
final float loadFactor;
通过查看hashmap的源码发现有两个问题
1 为什么每次扩容要是2的次方?
就是我们在hash运算的时候,为了让我们存储的数据尽可能的平均分布在不同的位置上,这样我们在get取值的时候,就非常快了o(1),所以我们刚开始的时候会把计算出来的hash值,进行取模运算(hash%n),但是java的开发者,发现 &(与)运算会比取模运算快很多,在满足在做与运算的时候得出的结果要和 取模运算得出的结果一样,那么我们就的保证数组的长度为2的N次方,这样我们才能实现 hash%n 计算的结果和 hash&(n-1)计算的结果几乎一致。(个人揣测作者。😅)
可能有人会问那如果不是2的次方会怎么样,看完下面的图,也许就明白了
2 为什么旧的数据不在原来的索引位置上,就在原来的索引位置+旧的数组长度 上?