JDK源码学习笔记~HashMap.put()
上一篇文章撸了Arrays.sort(),感觉受益匪浅,今天再来学习一下HashMap.put()的底层究竟是如何实现的.
入口案例
package test.hashmap;
import java.util.HashMap;
import java.util.Map;
public class TestHashMap {
public static void main(String[] args) {
// 入口一
Map<String, Integer> map = new HashMap<>();
// 入口二
map.put("11", 1);
map.put("22", 2);
map.put("33", 3);
map.put("44", 4);
}
}
new HashMap()
/**
* 通过入口一,我们会进入到HashMap类中
* 在HashMap的构造方法中,会构造一个默认初始容量为16的空HashMap,并且设置默认负载系数0.75
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // static final float DEFAULT_LOAD_FACTOR = 0.75f;
}
HashMap对象的创建就是这么简单,没有什么复杂逻辑,接下来我们就到入口二看一下这个方法到底是如何实现的!
put
public V put(K key, V value) {
/**
* 在put方法里,调用的是putVal方法,我们再跟过去看看
* hash(): 遍历key的每位字节,计算出key的哈希值(h = 31 * h + key[i]) ^(异或运算) 它的高16位(h >>> 16)
*/
return putVal(hash(key), key, value, false, true);
}
putVal
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) // p = 节点数组[i = (末位索引值 & key的哈希值)]
tab[i] = newNode(hash, key, value, null); // 创建一个常规(非树)节点
else {
Node<K,V> e; K k;
if (p.hash == hash && // p的哈希值等于当前存入元素的哈希值并且 key 相同
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode) // p 是TreeNode实例
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // putVal的树版本
else {
for (int binCount = 0; ; ++binCount) { // 遍历当前数组节点索引处链表
if ((e = p.next) == null) { // 当链表的下一个节点为空时创建新的节点
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // 阈值(TREEIFY_THRESHOLD): 8; -1 for 1st
treeifyBin(tab, hash); // 当前链表长度达到阈值时将链表转换成树
break; // 节点创建完毕结束遍历
}
if (e.hash == hash && // 如果当前节点与插入节点哈希值相同并且key相同则退出循环
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e; // 移动节点
}
}
if (e != null) { // 现有键映射
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e); // 允许LinkedHashMap后处理的回调
return oldValue; // 返回旧的value
}
}
++modCount; // 更新修改次数
if (++size > threshold) // 当数组的大小大于下一个要调整的阈值 (默认初始容量DEFAULT_INITIAL_CAPACITY为 16)
resize(); // 调整数组大小
afterNodeInsertion(evict); // 允许LinkedHashMap后处理的回调
return null;
}
resize
/**
* 初始化或增加表大小。
* 如果为空,则根据字段阈值中保持的初始容量目标进行分配。
* 否则,因为我们使用的是2的幂,
* 所以每个bin中的元素必须保持相同的索引,
* 或者在新表中以2的幂偏移。
*
* @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) { // MAXIMUM_CAPACITY = 1 << 30
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY) // DEFAULT_INITIAL_CAPACITY = 1 << 4
newThr = oldThr << 1; // 翻倍
}
else if (oldThr > 0) // 初始容量置于阈值
newCap = oldThr;
else { // 零初始阈值表示使用默认值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // DEFAULT_LOAD_FACTOR = 0.75f
}
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 { // 重新计算保存顺序
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;
}
putTreeVal
/**
* putVal的树版本。
*/
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab, int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this; // 判断树不为空则返回该树的根节点
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1; // 左节点
else if (ph < h)
dir = 1; // 右节点
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null && // 用于在hashCodes相等且不可比较时对插入进行排序
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null && (q = ch.find(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn); // 创建一个树节点
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x)); // 确保给定的根是其容器的第一个节点
return null;
}
}
}
treeifyBin
/**
* 除非表太小,否则将替换给定哈希值的索引中bin中所有链接的节点,
* 在这种情况下,将调整大小。
*/
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); // 将当前索引处树化
}
}
tieBreakOrder
/**
* 断头实用程序,
* 用于在hashCodes相等且不可比较时对插入进行排序。
* 我们不需要总订单,
* 只需一个一致的插入规则即可在再平衡中保持等价。
* 打破平局比必要的进一步简化了测试。
*/
static int tieBreakOrder(Object a, Object b) {
int d;
if (a == null || b == null ||
(d = a.getClass().getName().
compareTo(b.getClass().getName())) == 0)
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
-1 : 1);
return d;
}
balanceInsertion
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp); // 向左旋转
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp); // 向右旋转
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
treeify
/**
* 从数组中将当前索引处链表树化
*/
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
root = balanceInsertion(root, x); // 红黑树转换
break;
}
}
}
}
moveRootToFront(tab, root); // 将根节点移动到首位
}
红黑树方法,全部改编自CLR
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
LinkedHashMap后处理的回调
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
学着画了一张图理清思路, 感觉画的好乱, 还是得多练习才行
读了两遍, 还是懵懵懂懂的, 有错误的地方麻烦大佬们提醒一下我, 我马上更正, 因为现在还是处于初学阶段, 请多多包涵, 同时也希望大佬们多多指点下如何正确的进行源码阅读, 谢谢!