JDK源码分析系列--HashMap(1.8)
HashMap的存储结构
变量定义
/**
* 默认的初始化容量,必须是2的n次幂
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大的容量是2的30次幂
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认的负载因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 链表转红黑树的阀值,当HashMap中某一个槽位中的链表长度达到了这个阀值,那么链表可能会转化为红黑树,也可能直接扩容
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 红黑树退化为链表的阀值
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 最小的链表转化为红黑树的数组容量,如果链表达到了转红黑树阀值,但是数组(槽)长度还没有达到该阀值,那么要先扩容
* 为了避免扩容与树形化的冲突,该值不小于4*TREEIFY_THRESHOLD
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 哈希桶数组,首次使用的时候初始化,并根据需要调整大小,分配时,长度始终是2的n次幂
*/
transient HashMap.Node<K,V>[] table;
/**
* 保持缓存到entrySet()
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* HashMap 中实际存储的 key-value 键值对数量
*/
transient int size;
/**
* 此HashMap结构已经修改的次数,
*/
transient int modCount;
/**
* 用于判断是否需要扩容的阀值(capacity * load factor).
*
*/
int threshold;
/**
* 负载因子实际大小
*/
final float loadFactor;
链表结构
/**
* 基本的hash链表节点,用于大多数
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //定位数组索引位置
final K key; //元素的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;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
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;
}
}
putVal方法
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
//table为空或者length==0时,按照默认大小扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//通过(n-1)&hash来定位存储数组的下标i,如果该下标下没有元素时直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {//若i的位置上的值不为空,
HashMap.Node<K,V> e; K k;
//当前位置上的Node p的key与要插入的key相同,直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//当前节点时红黑树,直接在红黑树中插入该节点
else if (p instanceof HashMap.TreeNode)
e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//当前节点时普通链表,执行链表的插入
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {//遍历到最后一个节点,还没有匹配到key,则直接创建一个新节点添加到链表最后
p.next = newNode(hash, key, value, null);
//链表长度大于8时,需要进行链表转红黑树的处理
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
break;
}
//遍历中发现key已经存在直接覆盖value并退出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//已经存在该key的情况时,将对应的节点的value设置为新的value
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//插入成功后,判断实际存在的键值对数量 size 是否超多了最大容量 threshold,如果超过,进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize()
扩容方法
/**
* 初始化或者两倍哈希槽的大小。如果为空,根据默认的值初始化。
* 否则,由于是用2的n次幂,则元素的下标或者在和以前一致,或者移动到(当前index + 老capacity)位置
*/
final HashMap.Node<K,V>[] resize() {
// 将字段引用copy到局部变量表,这样在之后的使用时可以减少getField指令的调用
HashMap.Node<K,V>[] oldTab = table;
// oldCap为原数组的大小或当空时为0
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 如果超过最大容量1>>30,无法再扩充table,只能改变阈值
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 {//初始化
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;
// 创建容量为newCap的newTab,并将oldTab中的Node迁移过来,这里需要考虑链表和tree两种情况。
HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
table = newTab;
if (oldTab != null) {// 将原数组中的数组复制到新数组中
for (int j = 0; j < oldCap; ++j) {
HashMap.Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
// 如果e是该哈希槽的唯一一个元素,则直接赋值到新数组中
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof HashMap.TreeNode)
// split方法会将树分割为lower 和upper tree两个树,如果子树的节点数小于了UNTREEIFY_THRESHOLD阈值,
// 则将树untreeify,将节点都存放在newTab中。
// TreeNode的情况则使用TreeNode中的split方法将这个树分成两个小树
((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { //保持顺序
//创建两个链表用来存放要放的数据,
// hash值&oldCap为0的(即oldCap的1的位置的和hash值的同样的位置都是1,
// 同样是基于capacity是2的次方这一前提)为low链表,反之为high链表,
// 通过这种方式将旧的数据分到两个链表中再放到各自对应余数的位置
HashMap.Node<K,V> loHead = null, loTail = null;
HashMap.Node<K,V> hiHead = null, hiTail = null;
HashMap.Node<K,V> next;
do {
next = e.next;
// 按照e.hash值区分放在loTail后还是hiTail后
if ((e.hash & oldCap) == 0) {
// 运算结果为0的元素,用lo记录并连接成新的链表
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {// 运算结果不为0的数据,用hi记录
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 处理完之后放到新数组中
if (loTail != null) {
loTail.next = null;
// lo仍然放在“原处”,这个“原处”是根据新的hash值算出来的
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
// hi放在j+oldCap位置
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}