深入理解HashMap
HashMap是我们在开发中经常使用到的对象,那么你是否真的了解HashMap呢?我们先看下面几个问题:
- HashMap的结构是什么样子的?
- HashMap的默认容量是多少?
- HashMap在什么时候扩容?
大家先思考一下,上面的问题的答案,我们稍后慢慢揭晓,我们先来看两段代码:
public class HashMapTest{
public static void main(String[] args){
// #1
Map map1 = new HashMap();
// #2
Map map2 = new HashMap(19);
}
}
大家看上面的两段代码,猜一下#1 和 #2的HashMap容量是多少?
- #1的容量是16
- #2的容量是32
有人会疑惑,我设置了HashMap的容量是19,为什么#2的容量是32啊?这个,要看一下源码,如果,你设置了HashMap的容量,会把容量自动计算大于你设置的容量最近的2的幂数;例如,你设置的50,那么真实的容量是64。
jdk1.8中HashMap的结构,其实会有两种情况,一种是散列数组+链表,还有一种是散列数组+红黑树,默认情况下用的散列数组+单向链表结构,在链表的长度大于7的时候,会把列表转换为红黑树。请看源码:
// HashMap put方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//如果,散列数组的大小是0,就进行初始化
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//散列数组,没有下标冲突,并且当前位置为null,执行插入
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
// 下标冲突,key相同,替换value
e = p;
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);
// TREEIFY_THRESHOLD =8;所以,是链表长度大于7的时候 ,转红黑树
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)
// HashMap扩容
resize();
afterNodeInsertion(evict);
return null;
}
从上面的源码,我们可以确定,在jdk1.8中HashMap的数据结构。从源码里面,我们还看到了什么时候扩容,什么时候去初始化散列数据,分配内存空间。HashMap中put的流程大致如下:
- 散列表为空,进行初始化(HashMap是在put的时候,才给散列数组开辟内存空间的)
- 散列数据下标未冲突,并且当前位置为null,插入值
- 散列数组下标冲突,key相等,替换value
- 散列数组下标冲突,key不相同,添加到链表的尾部,如果,链表长度大于7,把链表转成红黑树
- 当散列数组的长度大于扩容长度的时候,HashMap就会扩容
通过查看源码,我们深入的理解了jdk1.8中HashMap的结构以及容量,我们在看看HashMap的扩容方法的源码
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;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// initial capacity was placed in threshold
else if (oldThr > 0)
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;
@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;
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;
}
从上面的源码,我们可以看出来,HashMap扩容的步骤如下:
- 散列数组长度为0,扩容伐值也为0,进行初始化,容量值取HashMap的默认值
- 散列数组长度为0,扩容伐值不为0,进行初始化,容量值取扩容伐值
- 散列数组长度大于0,进行扩容,容量是原来的2倍
- 扩容伐值 = 散列数组容量 * 扩容因子(默认0.75F)
还有一个重要的部分,就是数组下标的计算,源码如下:
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
从上面的源码和注释,我们知道,HashMap数据下标的计算方式。
深度思考:
从源码分析,我们深入的了解了HashMap,那么,现在请你回答如下问题:
- HashMap的数据结构是怎么样子的?
- HashMap默认数组容量是多少?默认的负载因子是多少?负载因子有什么用?
- 如果new HashMap<>(33),数组容量多大?
- HashMap的key的数组下标怎么算?
- HashMap 什么时候创建数组占用内存?数组下标碰撞怎么处理?
- HashMap什么时候扩容?
- HashMap为什么默认容量必须是2的幂数?
- 为什么HashMap是线程不安全的?