基本属性
// 初始化容量,必须要2的n次幂
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 负载因子默认值
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 需要从链表转换为红黑树时,链表节点的最小长度
// 依据泊松分布,单个链表超过8个元素的机率十分小了,所以为8;
static final int TREEIFY_THRESHOLD = 8;
// 转换为红黑树时数组的最小容量
static final int MIN_TREEIFY_CAPACITY = 64;
// resize操作时,红黑树节点个数小于6则转换为链表。
static final int UNTREEIFY_THRESHOLD = 6;
// HashMap阈值,用于判断是否需要扩容(threshold = 容量*loadFactor)
int threshold;
// 负载因子
final float loadFactor;
// 链表节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
// 保存数据的数组
transient Node<K,V>[] table;
// 红黑树节点
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
}
hash()
高16位于低16位异或,降低了hash冲突机率
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
tableSizeFor()
构造器可以传入初始容量参数,如果不是2的幂,会被转化成大于所传参数最接近的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;
}
put()
- 第一次添加元素时,table为null,初始化table数组
- 计算对应的数组下标
(n - 1) & hash
- 如果这个槽还没有数据,直接插入
- 如果key已经存在,替换value
- 如果该链表已经转换成红黑树,在树中插入元素
- 如果是链表,遍历链表,遇到相同key,替换value,否则在链表尾部插入元素(尾插法,防止出现死循环)
- 如果链表长度>8,转换为红黑树
- 最后判断是否超过阈值需要扩容
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 1. table 为 null,初始化哈希桶数组
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 2. 计算对应的数组下标 (n - 1) & hash
if ((p = tab[i = (n - 1) & hash]) == null)
// 3. 这个槽还没有插入过数据,直接插入
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 4. 节点 key 存在,直接覆盖 value
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 5. 该链转成了红黑树
else if (p instanceof TreeNode) // 在树中插入
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 6. 该链是链表
else {
for (int binCount = 0; ; ++binCount) {
// 遍历找到尾节点插入
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 链表长度大于 8 转为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 遍历的过程中,遇到相同 key 则覆盖 value
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;
// 7. 超过最大容量,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize()
因为扩容的新容量为旧容量的两倍,也就是二进制向左移一位,这样再进行(n - 1) & hash
计算分配桶的时候,就会有两种情况,一种是元素索引不变,一种是元素索引变成原索引+旧容量。
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;
}// 否则扩大为原来的 2 倍
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
// 初始化时,threshold 暂时保存 initialCapacity 参数的值
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 计算新的 resize 上限
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;
}
// 原位置偏移 oldCap 的子链表
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;
}
treeifyBin()
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); // 将链表转为红黑树
}
}
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}