前言
HashMap是Java中最常用的集合类框架,是Java语言中非常典型的数据结构。也是面试爱问的,下面博主会通过HashMap的源码深入分析这一数据结构。
1 HashMap源码分析
注:源码基于jdk1.8,与jdk1.7及之前版本有所区别
1.1 哈希表
分析HashMap源码之前,我们先大致了解一下数组、链表、哈希表的不同。
数组
对于数组,我们都很了解,它在内存中是一串连续的空间,所以,读的效率很高,但是删除或插入效率低,因为插入删除都可能引起其他数据的左移右移。
链表
占用内存宽松,空间复杂度小,时间复杂度O(N),插入删除都比较快,内存利用率高。
缺点就是查询效率比较低,得从第一个开始遍历。
哈希表
哈希表就是数组加链表的结合,取两者的优缺点做了一个结合与平衡。
1.2 put方法
进入put的源码后,第一个方法如下,
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这个方法的关键在hash(key)
,生成了key的hash值。
具体的生成逻辑是native实现,各位有兴趣可以去看看public native int hashCode();
然后用hash值的高16位与hash做 ^ 运算得到更加随机的低16位。
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
这样做的目的是为了计算出更加散列的下标,减少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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == 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))))
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);
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;
}
这个方法实现了HashMap put的核心操作。
第一步是声明,然后判断是否需要初始化table。初始化的结果是一个长度为16的Node数组。
然后,通过hash值计算出下标,如果那个下标位置没有数据,就把值添加进去。
如果有值,就处理冲突,
可以看到,
p.next
表明,它把值放到了链表的尾部,这样就是一个单向链表。
细心的人还会发现,后面有个if判断。
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
当长度大于等于8时,会走
treeifyBin
方法,里面有个判断,如果数值长度小于64,则进行扩容;超过64,将会把链表变成一个红黑树,提高效率。
这也是JDK1.8后做的一个变化,通过红黑树来提升效率!
1.3 get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
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;
}
取的逻辑就比较简单了,通过key的hash值计算数组下标,然后到那个下标位置的链表上去找,找到就返回,没有返回null。
2 谈谈HashMap的扩容机制
2.1 为什么需要扩容
这个问题其实很好回答。
因为Java8之前还是之后,HashMap存储相同hash值的key-value的越多,hash冲突带来的消耗就越多。所以,需要进行扩容,提升效率。
2.2 什么时候扩容
- 当达到阀值的时候扩容,阀值 = 数组长度 x 负载因子
- 当链表长度达到8,且数值长度小于64时会扩容数组。
2.3 JDK1.8的扩容策略
jdk1.7及之前的扩容策略较为简单,就是定义一个长度为当前table两倍的newTable,然后找到存在hash冲突的位置,遍历链表。依次根据hash值计算出该元素在新数组的位置,放过去即可。
JDK1.8之后,有所不同,下面是源码。
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) {
// 超过数组在java中最大容量,冲突就只能冲突
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;
@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) { // j位置上有元素,放到e中
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;
// 判断key的hash值与老数组长度与操作后结果决定元素是放在原索引处还是新索引
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);
// (e.hash & oldCap) == 0的所有节点形成的链表放到新数组j位置
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// (e.hash & oldCap) == 1的所有节点形成的链表放到新数组(j+老数组长度)位置
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
从源码中,我们可以看到1.8的计算策略更加优秀了。
用e.hash & oldCap
去计算元素在新数组中的位置,不需要再次计算hash,计算结果为0下标位置不变,不为0,下标位置 = 原数组长度 + 原下标位置。