概述
HashMap实现了Map<K, V>接口,通过键-值(key-value)的方式存取数据。内部的数据结构是数组+链表(或者Tree),插入时通过key的hash值,映射((n - 1) & hash,其中n为数组的长度)到数组中的位置,如果hash值重复,则在链表的末端插入(当一个链表中的数据大于等于8个时,就将链表转变为Tree),而当数组达到一定值时,会resize,重新创建一个数组,大小是之前的两倍;取出时,也是通过key的hash值,映射到数组的位置,如果刚好是第一个,则返回,否则一直查找到key相等的value并返回,如果还是没找到则分会null。
本文的目标是带着学习的态度,查看HashMap的源码,从put,get,resize三个方法分析它的内部实现。
HashMap数据结构
HashMap继承自AbstractMap<K,V>,实现了Map<K, V>接口(AbstractMap<K,V>也实现了这个接口,为什么没有冲突呢?):
Map接口有一个Entry接口,HashMap中内部类Node实现了Entry接口,数据就存放在:
Node<K,V>[] table;
HashMap内部定义了几个重要参数:
// 加载因子默认是0.75,取值越小,hash冲突概率越低,插入和查找速度愈快,但是占用的空间更多
final float loadFactor;
// 临界值,当Map的size大于这个值时会出发resize
int threshold;
put方法分析
调用put方法将数据插入到HashMap,因为HashMap是数组+链表(或者Tree),所以有三种情况,一种是数组对应索引位置没有数据,直接插入数组中;如果有数据了,判断这个元素是否是TreeNode,如果是则插入到Tree中,否则插入到链表中,并检查链表长度,一旦超过7则转换为Tree:
put方法调用了putVal:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
putVal方法:
- 先判断table是否初始化了,如果没有,则调用resize初始化;
- 判断key对应的hash的数组位置是否有数据,没有则新建一个Node,然后插入数组中;
- 如果hash冲突了,先判断数组索引下的元素是否是TreeNode,如果是,则插入到TreeNode;
- 如果不是,则插入到链表,并检查链表的长度,当链表长度为8时改链表为TreeNode
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;
}
get方法分析
分析了put方法,get是put的一个逆过程,先判断hash值映射的数组索引的元素的key是否一致,如果恰好是它,则直接返回;否则判断这个元素是否是TreeNode,如果是,则从Tree中获取,否则从链表中获取:
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;
}
resize方法分析
resize源码如下,resize的过程首先检查是否初始化了,如果没有,则初始化,如果已经初始化了,则新建一个数组,长度是原来的两倍,然后将旧数组中的元素插入到新数组中(链表或者Tree):
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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
}
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) {
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;
}
hash值与数组索引
看下面关于hash值的源码:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
从hash值映射到数组索引的代码在putVal:
i = (n - 1) & hash // 其中i是数组索引,n是当前数组的长度,hash是上面hash()函数返回的hash值
总结
- HashMap的数组结构是数组+链表(后面版本当链表长度大于7时改为红黑的结构);
- 影响HashMap性能的重要因素是loadFactor和threshold两个属性,loadFactor默认是0.75;
- 从key到数组索引的映射,需要key的hash经过一些列的运算;
- 当HashMap元素数量达到临界值threshold时,数组将会扩容,变为就数组的两倍;
- hash冲突时将元素插入到链表末端,减少hash冲突可以降低loadFactor,但是会增加数组冗余,这又回到了查询时间与空间的平衡问题;
- JDK1.8中HashMap如何应对hash冲突?这篇博客介绍了如何减少hash冲突