jdk8中的HashMap的底层源码解析
Node<K,V>[] tab; Node <K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
变量放在栈里,多次使用时会节约性能。 而直接使用table从堆里取,会浪费资源
数组的长度一定是2的幂次方数。哪怕传入一个初始容量不是2的幂次方,hashmap也会找到大于这个数字的2的次方数
多次使用位运算
put的时候,node数组的下标要求:
- 下标不能越界
- 尽可能雨露均沾
- 尽可能节约性能。
hashcode右移,是为了让高位也参与运算。
1.7是头插法,1.8链表是尾插法
put方法
public V put(K key, V value) {
//根据key计算hashcode,相对于JDK7中hash算法有所简化
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
//hashcode右移16位,是为了让高位也参与运算。
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
putVal方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//给tab赋值,并判断数组是否为null,如果是,则初始化数组,并得到数组大小n
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根据hashcode计算出对应的数组下标i,并判断该位置是否存在元素
//如果为null,则生成一个Node对象赋值到该数组位置
//否则,将该位置对应的元素取出来赋值给p
// 这里的(n-1) & hash 是精髓。数组的长度n一定是2的幂次方数。哪怕传入一个初始容量不是2的幂次方,hashmap也会找到大于这个数字的2的次方数。这样n-1的二进制数就是0001111这种类型,与 hash值可以得到一个在0~n-1的下标。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//如果该下标位置存在元素,则进行一系列判断
Node<K,V> e; K k;
//首先判断该下标位置存在的元素key是否和当前put进来的key相等。
//如果相等,则在后续代码中更新value,并返回oldValue
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果该下标位置存在的元素的类型是TreeNode,表示该位置存的是一颗红黑树
//那么就会把新元素添加到红黑树中,并且也会判断key是否已经在红黑树中
//如果存在则返回该TreeNode,并在后续代码中更新value
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//否则,该位置存的是一个链表,那么就要把新元素插入到链表中
//因为要看当前链表的长度,所以就需要遍历链表
//在遍历链表的过程中,一边记录链表上的元素个数,一边判断是否存在相同的key
//遍历到尾节点后,将新元素封装为Node对象并插入到链表的尾部
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//TREEIFY_THRESHOLD是变数门槛。超过8就会变成红黑树。因为循环条件是++binCount
//所以这里条件是 >= 8-1
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//判断key是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 如果key存在相同,则更新value,并返回oldValue
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)
resize();
afterNodeInsertion(evict);
return null;
}
resize
final Node<K,V>[] resize() {
// resize()包括数组初始化和扩容
// 记录当前数组信息
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
// 集散新数组的数组大小、扩容阈值
int newCap, newThr = 0;
// 如果老数组大小大于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;
//告诉编译器忽略rawtypes和unchecked警告
@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;
// 如果该位置上的元素是TreeNode,则对这棵红黑树进行转移
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;
}
split
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
// 由于红黑树是由链表改造而成,所以链表其实还是存在的。
// 对链表进行高低拆分
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
// 拆分之后,如果存在低位链表,则看链表长度,如果小于等于UNTREEIFY_THRESHOLD
// 则把节点类型改为Node类型。这里的长度是6
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
// 否则,把头结点转移到新节点(红黑树的根节点一定是链表的头结点)
tab[index] = loHead;
// 如果存在高位链表
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
// 和上面类似
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}