Hashmap底层数据结构
jdk1.7之前,Hashmap底层数据结构是数组+链表实现的,1.8之后采用了红黑树对Hashmap进行了优化。
jdk1.8后HashMap采用数组+链表+红黑树
的数据结构。
HashMap原理
在1.7之前,HashMap底层采用数组加链表的数据结构,当在数据量大的时候,出现hash碰撞的几率也随之增大,于是链表长度会变得长,而链表的增删操作十分不便。所以在1.8之后,当链表长度增加到一定长度(默认是8个节点)时,将链表优化为一颗自平衡二叉树(红黑树),大大提高了效率。
初始化
同样的,1.8的初始化也是类似1.7的懒加载,在向集合中添加元素时,才进行初始化,而1.8的扩容和初始化都是在resize()
方法中进行的。
添加元素
调用put()方法添加元素,真正执行的是putVal()
进行添加的。
- 在第一次添加时,会调用
resize()
方法进行初始化 - 根据元素的hash值计算出具体应该在该数组的那个index位置,并把该位置元素(该下标的首元素)赋值给
变量p
,这个p首元素
可能出现三种情况,1.该位置没有存任何元素、2. 该元素下是一个红黑树(超过默认链表长度优化为红黑树,那么这个元素就是一个树节点)、3. 该元素下面是一个链表
情况1:那么就直接创建结点、存入带插入元素
情况2:向树中添加元素
情况3:遍历链表,并向尾部添加
该元素。尾插法
,if ((e = p.next) == null) {p.next = newNode(hash, key, value, null);
这里与1.7有不一样。这时还会去判断此时链表长度是否达到了要优化为红黑树的时机。if (binCount >= TREEIFY_THRESHOLD - 1) ;treeifyBin(tab, hash);
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//参数hash就是待插元素的hash值
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断当前数组是否已经进行了初始化,第一次时肯定是null
if ((tab = table) == null || (n = tab.length) == 0)
//没有初始化,就去初始化空间,扩容数组,并且把容量长度赋值给n
n = (tab = resize()).length;
//1.(n - 1) & hash:是计算当前元素的具体index值,让指针p指向这个位置
if ((p = tab[i = (n - 1) & hash]) == null)//表示当前index位置没有存储
//创建结点,放入该元素
tab[i] = newNode(hash, key, value, null);
//当前index位置(坑位)被占了
else {
Node<K,V> e; K k;
//2.判断当前key是否已经存在
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//当前key已存在
e = p;//替换旧值
//当前key不存在
//3.判断是否是红黑树
else if (p instanceof TreeNode)
//如果是红黑树,那么往树里插入元素(左旋、右旋等)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//4.不是红黑树,那么就遍历当前链表
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {//尾节点
p.next = newNode(hash, key, value, null);//创建结点并加到链表尾部
//TREEIFY_THRESHOLD-1默认是8,当链表长度>=8时,将链表转化为红黑树
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与迭代器,failfast有关
++modCount;
//判断当前hashmap容量是否到达扩容阀值
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
扩容机制
这个方法做了两件事,初始化和扩容,设置了变量newCap
,根据不同的时机,返回不同的Node数组。
- 初始化
- 扩容
扩容条件:当前hashmap容量是否到达扩容阀值
/*
* 初始化和扩容方法
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//判断原数组是否为null
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//Node数组已经初始化,扩容
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--2倍
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//进行数组初识化
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;//默认是1>>>>4,为16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//默认:0.75*16
}
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;
//若当前数组位置不为null有元素
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)//当前数组位置元素的next为null,重新计算位置直接添加
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)//当前数组位置元素的next为树节点
//将老数组的元素split打散,重新分配
((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 {//do--while循环
next = e.next;
//思考:为什么不是 e.hash & ( newCap - 1 ) ?
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;
}