1、HashMap数据结构
jdk8以前数据结构是数组+链表
jdk8及其以后数据结构是数组+链表+红黑树
在并发的情况下,发生扩容时,可能会产生循环链表,在执行get的时候,会触法死循环,引起CPU 100%的问题,所以一定要避免在并发环境下使用HashMap
2、HashMap为什么选取数组+链表+红黑树的数据结构
- 数组:存与取效率最高,时间复杂度为
O(1) - 链表:解决hash碰撞问题,查找操作需要遍历链表中的所有数据,时间复杂度为
O(n) - 红黑树:对链表性能进行优化,查找、插入、删除等操作时间复杂度为
O(logN)
3、为什么不直接使用红黑树而是在链表达到指定长度是才转换为红黑树?
元素个数较少,红黑树效率不如链表,红黑树平衡被打破,需要自旋(左旋、右旋)来维持树的自平衡
4、链表转红黑树的阈值是由来以及链表转红黑树的条件
阈值的由来: 通过泊松分布(概率统计)出现(1个元素、2个元素、3个元素)列表的概率来统计链表转换为红黑树的阈值
转换条件: 数组长度大于等于64且某个数组元素链表长度大于等于9时才会进行转换
5、为什么是数组长度达到64才可能会转换为红黑树?
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//todo 数组长度小于64时是不会转换为红黑树的
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
6、为什么是链表转红黑树的阈值是9而不是8?
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//todo 初始化大小(扩容操作)
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//todo 通过hash计算判断对应的数组元素是否有值
if ((p = tab[i = (n - 1) & hash]) == null)
//todo 没有则直接插入元素
tab[i] = newNode(hash, key, value, null);
else {
//todo 注意,到这里该hash值对应的数组元素中已经有一个元素了
Node<K,V> e; K k;
//todo 判断key是否存在,存在则覆盖旧值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//todo 判断是否为红黑树
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//todo 进入链表逻辑
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//todo 创建Node节点
p.next = newNode(hash, key, value, null);
//大于等于7,循环8次,创建了8个节点,加上之前已经存在的一个节点,链表长度为9才会进行红黑树转换
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)
resize();
afterNodeInsertion(evict);
return null;
}
7、为什么HashMap推荐数组的容量是2的指数次幂
容量初始化: 传入容量不是2的指数次幂,会转换为最接近于这个数的且大于这个数的2的指数次幂
为了提高效率,hashcode%length取模效率太低,位运算hashcode&(length-1)效率较高,jdk1.7版本数组扩容会产生大量的rehash
8、为什么负载因子是0.75?
为了解决hash碰撞问题
- 如果负载因子大于等于
1,碰撞可能性大,链表长度随之越长,查找时间复杂度越高(时间换空间) - 如果负载因子小于等于
0.5,查询快(空间换时间),hash碰撞低
0.75这个数值是根据牛顿二项式推倒出来的,在时间与空间上进行折中处理