【Java源码】JDK1.8 HashMap源码解析
对于我自己来说,平时在敲代码的时候用HashMap很频繁,键值对方便又快捷。HashMap是用来储存key—value(键值对)的集合,最常用到的就是put和get方法,抱着HashMap是如何实现的好奇心去读读HashMap的源码。
基本属性:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
其基本属性全部static final 限定
DEFAULT_INITIAL_CAPACITY = 1 << 4 默认容量 16
DEFAULT_LOAD_FACTOR = 0.75f 负载因子,调整扩容门槛 = 表长 x 0.75
MAXNUM_CAPACITY 最大容量,1<<30,左移运算,int为4字节,最高位是符号位,若,是1<<31,就会变负数,这是int能表达的最大数
TREEIFY_THRESHOLD 树化门槛 为 8 当到达这个值的时候会把链表转化为红黑树
UNTREEIFY_THRESHOLD 当桶中数组小于6 树转换回单链表
MIN_TREEIFY_CAPACITY 最小树化容量 为 64 未达到64时只扩容
我们可能最多用到的就是Map< xxx, xxx > map = new hashMap<>()这种用法了,所以先从这里看起
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
The load factor for the hash table 这是源码注释给出的关于loadFactor的解释 即哈希表的负载因子 这里将他赋值为0.75
put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
当把一个键值对put进map时,会调用putVal方法,他的第一个参数用到了hash(key)方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
我认为这个方法是取得一个hash值,通过它来进一步存储数据
进一步向下的同时,得先看一下Node<K,V>,这个内部类包含四个属性,hash值,键key,值value,以及下一个Node,本质上为一个链表,连接各个键值对
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, 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;
}
}
现在来专心看put方法内部的实现,我们在称Node为结点
每次put的时候都要取得由结点组成的数组 (哈希表),当哈希表不存在时,则需要新建表
根据哈希值在哈希表中寻找相应链,不存在则创建,并以此新结点为链表头
存在时则进行链表各节点的判断,相同覆盖,不相同则添加,源码具体实现思路见如下代码注释部分:
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;
// 哈希表中该位置key(键值)重复,即链表头的键重复,则覆盖之
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) {
// 两个判断: 1.如果中途有键值相等的键,则break;
// 2.如果遍历到尾,则新结点加到该链尾部,break;
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;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 更新p结点,便于继续遍历
p = e;
}
}
// 这里通过判断e结点来确定是否在链中找到相同的key
if (e != null) { // existing mapping for key
// 取出旧结点的value,便于返回;
// 用新结点覆盖旧结点
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// modCount 有了以前解析List源码的经验可知其作用一定是,防止迭代时的安全
++modCount;
// 每put进去一个,就要判断此时hashMap的大小
// 超过最大容量则就需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
JDK8中为避免链表太长,一旦该哈希值处的链表长度到达规定的树化门槛,则将该链表转化为黑红树,优化读取速度。
这其中要说到好几个方法,扩容resize,树化,以及如何将结点加入到红黑树中。
咱们先看 扩容 resize()
JDK8对hashMap扩容进行了优化
扩容的详细思路已经注释到代码中。总的来说,通过原哈希表定义分配新哈希表(容量,扩容门槛等),再将原表中索引取出放置进新表中。
final Node<K,V>[] resize() {
// 获取旧哈希表
Node<K,V>[] oldTab = table;
// 获取当前哈希表容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 获取当前门槛(到达此门槛扩容)
int oldThr = threshold;
// 初始化新容量和新门槛
int newCap, newThr = 0;
// 设置容量 和 门槛
// 分三种情况
// 1. 哈希表内有空间
if (oldCap > 0) {
// 1.1 原容量大于最大容量 1<<30
// 调整哈希表门槛为允许最大 1<<31 - 1 返回表
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 1.2 当前容量大于默认容量16 且 当前容量的两倍不超过最大容量 1<<30
// 新容量 = 旧容量 * 2
// 新门槛 = 旧门槛 * 2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 2. 哈希表无空间 有门槛
// 初始化哈希表容量
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 3. 哈希表无空间 无门槛
// 采用默认容量 16 默认门槛 16 * 0.75 = 28
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 2. 如果新门槛为0,若用户设置为0,则需要根据新容量设置新门槛
// 新门槛大小 = (int)(新容量 * 0.75)
// 一但新容量或新门槛大于最大容量,则立即设置新门槛大小为允许最大容量
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
// 3. 更新哈希表
@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;
// 3.1 取出数据链,即链头,并将旧表空间置空,以便与GC回收
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 3.1.1 若该链只有一个键值对
// 直接放置到新哈希表中
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 3.1.2 若该链是红黑树,就需要将旧树转存到新表中
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 3.1.3 若该链含有多个数据,且不为红黑树
// 将旧链数据转存至新表中
else { // preserve order
// 下面是Jdk8优化“重哈希”的代码段
// 这里的思路很巧妙
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 {
// 原位置(索引) + oldCap
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 原索引加到新链中
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 原索引+oldCap 加到新链中
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
看到源码的优化重哈希代码的时候,我也突然丈二和尚摸不着头脑起来了,查阅了一些资料,算是搞明白了。
通过源码,我们可以得知,我们每次将容量拓展为原来的两倍,所以,现在表中的元素要么在原位置上,要么在原位置再移动原大小的位置上。
请看下图:
n为哈希表的长度
图(a)表示扩容前的key1和key2两种key确定索引位置的示例。
图(b)表示扩容后key1和key2两种key确定索引位置的示例,其中hash1是key1对应的哈希与高位运算结果。
在扩容之后,哈希表的长度变为原来的两倍,和key按位&的时候,它所“标记”的也多了一位,新的下标就会发生变化,但是,也仅仅只是在“1”时发生变化(原来下标 + 原表长),“0”时下标并不会发生变化,所以需要分类讨论。
扩充HashMap的时候,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”。下图是16扩充为32的重哈希过程图。
以上关于resize重哈希优化的思想启发于:http://www.importnew.com/20386.html
下面来看一下树化方法treeifyBin(Node<K,V>[] tab, int hash)
上面说到,当表中哈希值所对应的链长大于树化门槛8时,为优化存取效率,将此链转化为红黑树
下面这个方法主要完成的事是:将哈希值对应链的各结点转化为红黑树结点的类型,并设置为双向链,方便真正树化操作treeify(Node<K,V>[] tab);
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 判断 若表长小于最小树化容量,我们不做链转化为树的处理,而是选择resize
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);
// 用tl是否为空判断此时p是否为“头”
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);
}
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;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
// ......若干方法
}
从上述代码中不难发现TreeNode附加属性还有父结点,左孩子,右孩子,前驱结点,颜色
下面则是真正树化的方法:
遍历以上所得双向链,根据每个结点的哈希值来构成树
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
// 遍历以hd为头的链
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;
// 根hash值 与 当前hash值 比较
// 当前hash值 < 根hash值 dir设置为-1 意为在根左
// 当前hash值 > 根hash值 dir设置为 1 意为在根左
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
// 当前hash值 == 根hash值
// 如果节点的键不是Comparable类,
// 或者两个节点键比较的结果为相等,就强行让比较结果不为0
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
// 根据比较结果dir 判断在左子树还是右子树
// 子树为null时即查找结束,将结点作为叶子插入
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);
}
如何更新红黑树结构?
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;;) {
// 1.若插入结点的父不存在,
// 即该结点为根,设置其颜色为黑,并返回之
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
// 若插入结点的父结点为黑,且父节点并无父
// 不需要调整
else if (!xp.red || (xpp = xp.parent) == null)
return root;
// 2.若插入结点的父结点 是 该父结点的父的左孩子
if (xp == (xppl = xpp.left)) {
// 2.1 若该父结点父的右孩子存在 且 为红 图2.1
if ((xppr = xpp.right) != null && xppr.red) {
// 设置该父结点父的右孩子为黑
xppr.red = false;
// 设置该父结点为黑
xp.red = false;
// 设置该父的父为红
xpp.red = true;
// 将插入的结点设置为该父的父
// 代表以xpp结点为父的树已经整理完毕
// 更新x方便继续向上整理
x = xpp;
}
else {
// 2.2 若插入结点为该点父结点的右孩子 图2.3
if (x == xp.right) {
// 左旋
root = rotateLeft(root, x = xp);
// 更新xpp(父的父)
xpp = (xp = x.parent) == null ? null : xp.parent;
}
// 2.3 若插入结点的父存在
if (xp != null) {
// 设置其父为黑
xp.red = false;
// 若其父的父存在
if (xpp != null) {
// 设置其父的父为红
xpp.red = true;
// 右旋
root = rotateRight(root, xpp);
}
}
}
}
// 2.若插入结点的父结点 不是 该父结点的父的左孩子
else {
// 插入结点的父的父的左孩子存在 且 为红
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
// 整理完毕,更新x
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);
}
}
}
}
}
}
采用迭代上浮的方式,加上左旋和右旋的处理,使红黑树一步步变得稳定
左旋:
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;
}
当然,表里保存的各链若为红黑树,就必须要保证其链“头”为红黑树的根
所以就需要 moveRootToFront(Node<K, V>[] tab, Node<K, V> root) 方法
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
if (root != first) {
Node<K,V> rn;
// 设置索引在根上
tab[index] = root;
TreeNode<K,V> rp = root.prev;
// 如果根的next存在,设置这个next的前驱为根的前驱
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
// 如果根的前驱存在,设置前驱的next为根的next
if (rp != null)
rp.next = rn;
// 如果first存在,first前驱为根
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
get方法,即从哈希表中根据键找到值
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;
}
相比于put,get方法就显得很轻松而便于理解了,无非就是根据哈希值来寻找。
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
总结:
1.hashMap初始容量为16
2.每次扩容容量 乘 2
3.到达阀值会扩容,并更新阀值 = 表长 x 负载因子,负载因子默认0.75
4.hashMap非线程安全