HashMap
HashMap的实现
HashMap的实现通常分为两个版本,JDK 1.8之前和之后
在JDK1.7的时候HashMap采用的是数据+链表的形式,也就是通过拉链法的形式去解决hash冲突
到了JDK1.8的时候改成了数组 + 链表 + 红黑树的形式来实现,主要是解决链表过长带来的查询效率过低的问题,也就是在链表长度大于8时转换成红黑树的实现。
这里就会有一个问题—> 为什么是红黑树?
- 首先是AVL树与红黑树的对比
- 红黑树追求部分平衡,通过部分平衡来换取赠删节点时旋转次数的降低
- 红黑树,读取略逊于AVL,维护强于AVL,空间开销与AVL类似,内容极多时略优于AVL,维护优于AVL。
- B,B+树和红黑树的对比
- B和B+树一般是用在数据在磁盘上存储的情况,减少层数降低IO次数
- B+树在数据量不是很多的情况下,数据挤在一个范围内的话会退化成链表
推荐看一篇文章
(18条消息) HashMap为什么选择红黑树?_技术砖家–Felix的博客-CSDN博客_hashmap为什么要用红黑树
一些扩展
- 当桶长度大于64,链表长度大于8时会转化成红黑树
- 链表长度小于6的时候会退化回链表
put方法(jdk1.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;
//table未初始化,长度为0的时候会进行扩展
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 通过(n - 1) & hash 判断出桶位置的时候,桶出无节点将节点插入到桶中
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//如果key相等,且equals判断两个对象相等的话,用e记录
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//key不相等 是树节点的话进行树的插入操作
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);
// 结点数量达到阈值(默认为 8 ),执行 treeifyBin 方法
// 这个方法会根据 HashMap 数组来决定是否转换为红黑树。
// 只有当数组长度大于或者等于 64 的情况下,才会执行转换红黑树操作,以减少搜索时间。否则,就是只是对数组扩容。
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;
}
}
// 表示在桶中找到key值、hash值与插入元素相等的结点,覆盖
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;
}
整体流程就是
get方法(jdk1.8)
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 看第一个元素是不是
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
//从树中找
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
//从链表找
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
resize方法
将数组扩容为原来的二倍,然后将元素一个一个rehash()插进去
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 超过最大值就不再扩充了,就只好随你碰撞去吧
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 没超过最大值,就扩充为原来的2倍
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 {
// signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 计算新的resize上限
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) {
// 把每个bucket都移动到新的buckets中
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 {
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;
}
// 原索引+oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 原索引放到bucket里
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 原索引+oldCap放到bucket里
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
一些老生常谈的问题
jdk1.7中的死链问题
在jdk1.7中采用的是头插法进行插入节点,在多线程情况下
一个线程在扩容之后重新插入数据,变成
这样就导致在一个线程(t2)处B的next是A,另一个线程(t1)A的next是B,当t1再去进行扩容时的时候,会出现A的next是B,B的next是A的情况,出现一个死循环。
从源码来看
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
//获得当前结点的下一个节点 e = A next = B
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//获取rehash后的位置
int i = indexFor(e.hash, newCapacity);
//将A插入到新数组
e.next = newTable[i];
newTable[i] = e;
// 让 A ---> B,但是扩容完的线程是 B ---> A,出现死循环
e = next;
}
}
}
最关键的问题还是线程1可以读到线程2对table的最新修改
在jdk1.8的时候改成了尾插法,解决了死链的问题,但多线程情况下还是会有数据覆盖的问题,所以hashmap是线程不安全的
为什么table的长度是2的幂次方
这是因为当计算出散列值范围时-2147483648 到 2147483647加起来大概是40亿的长度,这个长度内存是放不下的所以一般会对数组长度取余,而
取余(%)操作中如果除数是 2 的幂次则等价于与其除数减一的与(&)操作(也就是说 hash%length==hash&(length-1)的前提是 length 是 2 的 n 次方;)。” 并且 采用二进制位操作 &,相对于%能够提高运算效率,这就解释了 HashMap 的长度为什么是 2 的幂次方
参考文章
Java集合常见知识点&面试题总结(下) | JavaGuide