HashMap源码分析
本文针对JDK1.8的HashMap进行粗浅的分析,如有什么问题,还望指正。
1.变量 & 默认参数
1.1 常量参数
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 默认初始化大小
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容积
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认装填因子
static final int TREEIFY_THRESHOLD = 8;//普通节点转为红黑树节点阈值,如果链表长度大于8则转红黑树存储。
static final int UNTREEIFY_THRESHOLD = 6;//红黑树节点转为普通节点阈值,如果链表长度小于6则转普通节点存储。
static final int MIN_TREEIFY_CAPACITY = 64;//在转变成树之前,还会有一次判断,只有键值对(table的容量)数量大于 64 才会发生转换。这是为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表中而导致不必要的转化。
1.2 成员变量
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
int threshold;
final float loadFactor;
capacity 译为容量。capacity就是指HashMap中桶的数量。默认值为16。一般第一次扩容时会扩容到64,之后好像是2倍。容量都是2的幂。
size 表示HashMap中存放KV的数量(为链表和树中的KV的总和)。
threshold 表示当HashMap的size大于threshold时会执行resize操作。 threshold=capacity*loadFactor
loadFactor 装载因子用来衡量HashMap满的程度。loadFactor的默认值为0.75f。计算HashMap的实时装载因子的方法为:size/capacity,而不是占用桶的数量去除以capacity。
2.基本结构
HashMap的底层主要是基于数组和链表来实现的,它之所以有相当快的查询速度主要是因为它是通过计算散列码来决定存储的位置。HashMap中主要是通过key的hashCode来计算hash值的,只要hashCode相同,计算出来的hash值就一样。如果存储的对象对多了,就有可能不同的对象所算出来的hash值是相同的,这就出现了所谓的hash冲突。学过数据结构的同学都知道,解决hash冲突的方法有很多,HashMap底层是通过链表来解决hash冲突的。
Notice: 如果链表结点大于8,转为TreeNode (红黑树)存储。
3.核心方法
3.1 tableSizeFor 方法
tableSizeFor 方法获取能容纳cap的最小2次幂。例如:cap = 10,return 16。
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
3.2 hash方法
JDK1.7下的hash方法
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
这样设计保证了对象的hashCode的32位值只要有一位发生改变,整个hash()返回值就会改变,高位的变化会反应到低位里。
JDK1.8下的hash方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这样设计保证了对象的hashCode的高16位的变化能反应到低16位中,相比较而言减少了过多的位运算,是一种折中的设计。
3.3 resize方法
resize方法执行流程:
根据当前table的状态获取新的table的容量和阈值。
根据新的容积创建新的table,并对原来的table的key重新根据hash值找到相应位置(newTab[e.hash & (newCap - 1)] = e;)
对于调整后的table的key对应的每一个链表,判断每个节点需不需要调整(e.hash & oldCap) == 0),并对需要进行调整的节点进行重新链接。
Node<K,V> loHead = null, loTail = null; //存储还在原始key对应的链表的头节点和尾节点。
Node<K,V> hiHead = null, hiTail = null;//存储需要调整到新的key的头节点和尾节点。
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;//新的key
}
}
}
}
}
return newTab;
}
3.4 putVal方法 & put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
putVal参数含义:
* @param hash:键的hansh值
* @param key:Key值
* @param value: Value值
* @param onlyIfAbsent:如果Key存在是否覆盖value值
* @param evict:如果为false,则表示初始化过程
putVal方法执行流程:
- 如果table为空,则调用resize方法初始化table,n为table的长度。
- 通过hash值&(n-1)去找到其在table 的位置,如果没有,则创建节点。
- 如果在table中找到,则在链表中找到hash值相同,key值也相同的节点,(期间判断节点类型:TreeNode、普通节点)
- 如果在链表/红黑树中没有找着节点,则创建一个节点。
- 最后对于key值之前就存在的通过onlyIfAbsent判断是否更新值。
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;
}
3.5 getNode方法&get方法
getNode方法执行流程:
- 根据hash & (n - 1)获取table的位置index,判断table[index] 的key是否相等。如果相等返回该node。
- 遍历table[index]连接的链表节点,找到与key相等的node,如果找到,返回该node,否则返回null。
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;
}
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
3.6 treeifyBin方法
treeifyBin方法执行流程:
- 判断当前table的capacity 是否大于MIN_TREEIFY_CAPACITY,如果小于做正常的resize();
- 循环将节点替代为红黑树。(未完成)
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
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);
}
}
4.杂项
- HashMap采用链地址法解决Hash冲突,在扩容resize时根据hash&(newCap - 1)重新计算key 的位置,并对其后链接节点进行调整。
- 当满足,链接节点大于TREEIFY_THRESHOLD (默认等于8)且table的capacity 大于 MIN_TREEIFY_CAPACITY (默认等于64)是触发链表转红黑树过程。
- 为什么HashMap默认大小必须是2的幂,源码上看,元素取模获取桶地址采用与(默认大小值-1)位与。默认大小值-1为全1,不同的key算的index相同的几率较小,数据分布均匀,碰撞几率小。如果默认大小不为2的幂,例如15,15-1 = 1110,最后以为永远为0,部分地址访问不到,造成空间浪费。