逐行分析HashMap核心源码
一、HashMap继承体系
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
HashMap
继承AbstractMap
抽象类,实现了Cloneable
和Serializble
接口
二、Node节点以及底层存储结构
Node
节点是声明在HashMap
内部的一个静态内部类
static class Node<K,V> implements Map.Entry<K,V> {
//将key的hash按照一定规则扰动存放
final int hash;
//键
final K key;
//值
V value;
//指针,用于链表连接下一个节点
HashMap.Node<K,V> next;
//构造方法
Node(int hash, K key, V value, HashMap.Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
//返回Node节点对应的Key
public final K getKey() { return key; }
//返回Node节点对应的Value
public final V getValue() { return value; }
//重写toString
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
Node
数组+链表+红黑树
扰动函数:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
在put
新节点时,Node
节点里面存放的hash
值是经过扰动函数后的值,主要目的是让hash值的高16位也参与运算,让hash值更散列,避免大面积hash碰撞
三、HashMap重要参数
//默认数组大小 16
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;
//树化阈值(当链表长度 >= 8 时,链表转化为红黑树)
static final int TREEIFY_THRESHOLD = 8;
//树降级为链表的阈值(当链表长度减少为6时,树转化为红黑树)
static final int UNTREEIFY_THRESHOLD = 6;
//树化阈值(当数组长度达到64时,链表达到8时才能转化为红黑树)
static final int MIN_TREEIFY_CAPACITY = 64;
/* ---------------- Fields -------------- */
//数组
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
//当前hash表元素个数
transient int size;
//当前hash表结构变化次数,当节点发生变化(删除,修改)时,modCount+1
transient int modCount;
//扩容阈值,当hash表元素个数达到阈值时,触发扩容
//threshold = capacity(数组长度) * loadFactor
int threshold;
//负载因子
final float loadFactor;
四、HashMap构造函数
/**
*
* @param initialCapacity 初始化数组长度,这里的长度必须为2的次方倍
* @param loadFactor 负载因子
*/
public HashMap(int initialCapacity, float loadFactor) {
//校验初始化数组长度不能小于零
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//校验初始化数组长度,不能超过数组阈值
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//校验负载因子,不能小于零或者非数
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//负载因子赋值
this.loadFactor = loadFactor;
//计算初始化数组,使其为2的次方
this.threshold = tableSizeFor(initialCapacity);
}
//目的是将设置的初始化数组长度计算成2的次方
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;
}
操作 | 原始值 | 结果值 |
---|---|---|
n >>> 1 | 1xxxxxxx | 01xxxxxx |
位或操作 | 1xxxxxxx | 01xxxxxx | 11xxxxxx |
n >>> 2 | 11xxxxxx | 0011xxxx |
位或操作 | 11xxxxxx | 0011xxxx | 1111xxxx |
n >>> 4 | 1111xxxx | 00001111 |
位或操作 | 1111xxxx | 00001111 | 11111111 |
n >>> 8 | 11111111 | 00000000 |
位或操作 | 11111111 | 00000000 | 11111111 |
n >>> 16 | 11111111 | 00000000 |
位或操作 | 11111111 | 00000000 | 11111111 |
因为Java中一个int占32位,这样最大无符号向右移动16位之后可以保证,输入的整型二进制数第一个1之后的所有为均为1。
为什么cap要减一?
移位操作能够保证第一个1后面全部是1,也就是得到的值是全1 + 1,但是有个例外,如果cap = 2的次方数时,比如cap = 16
//cap没有-1
//会发现最后得到的值比原来的2次幂大了1倍,造成了空间的浪费
cap = 16
10000 | 01000 = 11000
11000 | 00110 = 11110
11110 | 00001 = 11111
11111 | 00000 = 11111
11111 | 00000 = 11111
n = 11111 = 31
return 31 + 1 = 32
//cap-1
cap = 16
n = 16 - 1 = 15
1111 | 0111 = 1111
1111 | 0011 = 1111
1111 | 0000 = 1111
1111 | 0000 = 1111
1111 | 0000 = 1111
n = 1111 = 15
return 15 + 1 = 16
五、HashMap中put源码执行流程
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
hash()
函数上面已经说明了,相当于reHash
,让hash
值的高16位
也参与进来运算,充分扩散,降低hash
碰撞
下面看看put
核心方法putVal()
:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab存放数组
//p代表当前散列表元素
//n代表散列表数组长度
//i代表路由寻址结果
Node<K,V>[] tab; Node<K,V> p; int n, i;
//懒初始化,当调用put方法时才初始化散列表,防止new出来不使用浪费内存
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//由(n-1)& hash 寻址到的桶位恰好是null时,直接封装Node放进去
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//e:不为null的话,说明找到了一个与当前节点一致的元素
//k:表示一个临时的key
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 尾
p.next = newNode(hash, key, value, null);
//判断是否达到树化条件(8)
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;
}
}
//e != null条件成立,说明节点重复,做替换操作
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中resize扩容
final Node<K,V>[] resize() {
//oldTab:扩容前的散列表
Node<K,V>[] oldTab = table;
//oldCap:扩容前散列表的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//oldThr:扩容前散列表的阈值
int oldThr = threshold;
//newCap:扩容之后散列表的长度
//newThr:扩容之后散列表的阈值
int newCap, newThr = 0;
//条件成立说明已经初始化过了,是一次正常的扩容
if (oldCap > 0) {
//扩容之前的大小已经达到了最大则不扩容,将阈值设为int的上限
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//扩容之前的大小左移一位相当于 * 2 赋值给newCap,newCap小于数组最大长度 且 oldCap大于默认长度
//这种情况下则下一次阈值 = 这次的阈值左移一位(相当于翻倍)
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//oldCap = 0 说明散列表中为null
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//oldCap = 0,oldThr = 0
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//newThr为零时,通过newCap * loadFactor计算出newThr
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"})
//用新的cap创建出一个更长的数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//说明本次扩容之前,table不为null
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
//当前Node节点
Node<K,V> e;
//说明当前桶位有数据,但是不知道是单个元素还是链表还是红黑树
if ((e = oldTab[j]) != null) {
// 原来的数据赋值为null 便于GC回收
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;
// 高位链表:扩容之后数组的下标位置等于当前数组下标位置 + 扩容之前数组的长度oldCap 时使用
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中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) {
//tab:引用当前hash散列表
//first:散列表中头元素
//e:临时node元素
//n:数组长度
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//判断当前数组不为空 且 当前hash路由到的桶位不为空
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;
//判断当前桶位的next是否为null
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);
}
}
//未找到,返回null
return null;
}