JDK1.8的HashMap中数据结构:数据+链表+红黑树
为什么是红黑树而不是其它树
1.8中添加红黑树归根到底还是为了提升HashMap的效率,包括查询、插入、删除操作,此处最有争议也是面试最容易问到的是Doug Lea为什么不选择AVL树,两者相比AVL更加严格平衡,这也意味着AVL最大深度要比红黑树要小,能提供更快的查询速度,正因为完全平衡在节点有所变化后旋转操作更加复杂,插入性能偏低。Doug Lea最终选择了一种折中方案,当然效率也更加稳定。
put方法
HashMap的构造方法在执行时会初始化一个数组table,大小为0。在进行put方法是初始化数组大小,默认为16,可以调用HashMap的有参构造方法由你来指定一个数组的初始化容量,但是注意,并不是你真正说了算,比如你现在想让数组的初始化容量为6,那么HashMap会生成一个大小为8的数组,如果你想数组的初始化容量为20,那么HashMap会生成一个大小为32的数组,也就是你想初始化一个大小为n的数组,但是HashMap会初始化一个大小大于等于n的二次方数的一个数组。看完put的代码后再说为什么是2的幂次方。
//java.util.HashMap#put
//算出key的hash值,执行真正的put操作
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//java.util.HashMap#hash
//对key进行hash得到int类型的hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//java.util.HashMap#putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
//初始化Node数组、Node
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断table的大小是否为0,如果为0则会进行真初始化,也叫做延迟初始化。
if ((tab = table) == null || (n = tab.length) == 0)
//进行真初始化,数组的默认大小为16,这里更推荐使用构造方法指定数组大小
n = (tab = resize()).length;
//通过之前计算出来的key的hash值来确定要放到数组的哪个下标里,
// 此处也就是我们理解 (hash%table.size)的hash值对数组大小取余来确定数组下标,
// 但此处hashmap并没有这么做,说到底还是 逻辑与 要比 取余 效率要高,
// (n - 1) & hash 此处算下标的操作是依赖于数组的大小是2的幂次方,稍后会单独解释。
//判断tab[i]是否为空,如果为空(没有哈希碰撞)说明此处还没有存放Node对象,直接
new 一个Node对象赋值给tab[i]。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//此处不为空(发生哈希碰撞),存在三种情况:
/// 1、node对象(第一元素)
/// 2、红黑树
/// 3、链表
else {
Node<K,V> e; K k;
//第一种情况
//此处node对象的第一个元素就找到了
//判断key是否相同,如果相同代表hashmap对象中已经存在这个key的键值对
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//第二种情况
//tab[i]是个红黑树,进而进行红黑树的插入
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//第三种情况
//tab[i]是个链表,循环链表,在此期间判断是否要将链表改成红黑树,条件是:
//1、当链表中的元素个数大于8(第9个元素要插入时)
//2、数组的长度大于等于64
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
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;
}
}
//判断是否tab[i]元素下已经存在此key,如果存在就替换掉,返回原来的value
if (e != null) { // existing mapping for key
V oldValue = e.value;
//onlyIfAbsent是在java.util.HashMap#put传进来的值,默认为false
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//判断是否需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//java.util.HashMap#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);
}
}
为什么数组大小必须是2的n次方数
假如此处写个hash的二进制数11011001,此时我们的length为00010000(16的二进制表示),h & (length-1)
:
h: 1101 1001
15: 0000 1111
h&15: 0000 1001
15的低位上全是1,事实上2^n-1的二进制数低位上都是1,逻辑与的规则是都为1时才为1,h&15=0000-1111
。
得出的结论h&(2^n-1)结果范围在0-(2^n-1)
,这就是为什么在真初始化HashMap的时候,对于数组的长度一定要是二次方数,二次方数和算数组下标是息息相关的,而这种位运算是要比取模更快的。
对红黑树的操作
上文提到当链表元素个数大于8且数组大小不小于64时将链表修改成红黑树
java.util.HashMap.TreeNode#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;
// 判断待插入结点应该插入在左子树还是右子树
// 先比较hash值
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
// 如果hash值相等,然后比较k.compareTo(pk)
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
// 如果还相等则再比较identityHashCode
//identityHashCode为类重写之前的hashcode
dir = tieBreakOrder(k, pk);
// 根据dir的值就知道了待插入结点该插在左子树还是右子树了
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);
}
balanceInsertion(root, x)
,当执行到这一步时,要真正把对其变成红黑树,红黑树作为实践抽象出来的产物,一定有他的规律,HashMap通过这些规律进行变色旋转。具体做法是,将新结点的 color 赋为红色,然后以BST的插入方法插入到红黑树中去。设要插入的结点为N,其父结点为P,其 祖父结点为G,其父亲的兄弟结点为U,调整时分以下三种情况:
- 新结点N的叔叔结点U是红色的
处理方式是:将P和U修改为黑色,G修改为红色
。 - 新结点N的叔叔结点U是黑色的,且N是左孩子。
处理方式:对祖父结点G进行一次右旋转 新结点N的
- 叔叔结点U是黑色的,且N是右孩子。
处理方式:对P进行一次左旋转,就把问题转化成了第二种情况
java.util.HashMap.TreeNode#balanceInsertion
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
// 新节点默认为红色
x.red = true;
// xp表示x的父结点,xpp表示x的祖父结点,xppl表示xpp的左孩子结点,xppr表示xpp的右孩子结点
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
// 如果x没有父结点,则表示x是第一个结点,自动为根节点,根节点为黑色
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
// 如果父结点不是红色(就是黑色),或者x没有祖父节点,那么就证明x是第二层节点,父节点为根节点
// 这种情况无需就行操作
else if (!xp.red || (xpp = xp.parent) == null)
return root;
// 进入到这里,表示x的父节点为红色
// 如果x的父节点是祖父结点的左孩子
if (xp == (xppl = xpp.left)) {
// 祖父结点的右孩子,也就是x的叔叔节点不为空,且为红色
if ((xppr = xpp.right) != null && xppr.red) {
// 父节点和叔叔节点都为红色,只需要变色,且将x替换为祖父节点然后进行递归
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
// 如果叔叔节点为空,或者为黑色
else {
// 如果x节点为xp的右孩子
if (x == xp.right) {
// 先进行左旋,并且把x替换为xp进行递归,在左旋的过程中产生了新的root节点
root = rotateLeft(root, x = xp);
// x替换后,修改xp和xpp
xpp = (xp = x.parent) == null ? null : xp.parent;
}
// 如果x本来是左孩子,或者已经经过了上面的左旋之后,进行变色加右旋
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
// 如果x的父节点是祖父结点的右孩子
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);
}
}
}
}
}
}
左右旋转
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
// pp是祖父结点
// p是待旋转结点
// r是p的右孩子结点
// rl是r的左孩子结点
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
// 如果rl不为空,则设置p.right=rl
if ((rl = p.right = r.left) != null)
rl.parent = p;
// 如果祖父结点为null,那么r设置为黑色,r左旋之后即为root节点
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;
}
扩容
当阈值满足条件后会对当前Node数组进行扩容,扩容方法中包括对数组的初始化
//java.util.HashMap#resize
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//oldCap:老数组大小 oldThr:老数组阈值
//newCap:新数组大小 newThr:新数组阈值
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;
}
//进行数组扩容,newCap = 2*oldCap
//当oldCap>=16进行修改阈值,newThr = 2*oldThr,如果不成立即进入if (newThr == 0)
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 {
//oldCap = 0 对数组进行初始化,使用默认的数组大小1 << 4,根据加载因子算出阈值
// zero initial threshold signifies using defaults
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;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
//循环Node数组
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);
//链表
//数组扩容到2倍后,要对所有元素进行重新hash,进而找到所在的数组下标
//数组大小是2^n数,计算下标的算法是hash&(2^n-1),基于这种算法特性,oldTab[j]下的
//所有元素重新hash后在新数组上会出现两个固定位置newTab[j],newTab[j+oldCap],可能这就是算法的魅力吧
//下边的操作就是找出分别在newTab[j],newTab[j+oldCap]的元素,将其转移到newTab上
else { // preserve order
//此处理解为loHead是newTab[j]上的,hiHead 为newTab[j+oldCap]上的
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//找出分别在newTab[j],newTab[j+oldCap]的元素
//e.hash & oldCap 这个操作只有两种结果1或者0
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]
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
//放到newTab[j + oldCap]
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
//java.util.HashMap.TreeNode#split
//对红黑树元素转移
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
//lc,hc记录两个红黑树容器的数量,用于判断转移后是链表还是红黑树
int lc = 0, hc = 0;
//接下来对红黑树进行遍历,之前提到过TreeNode既是红黑树,也是双向链表,此处就是利用链表来遍历
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
//lc<=6 将loHead改为链表付给tab[index]
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
//此处如果进来证明hiHead 是有元素的,如果进不来证明重新hash后所有元素都在loHead上
//树化方法,上面已经介绍
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
get方法
如果理解了put方法,那get方法就非常简单了
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//进行非空判断,如果不成立直接返回空
//算出来的tab[i]上不为空
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;
//上文中已经讲过Node和TreeNode都有next属性
//判断该元素还有没有下一个元素,如果没有,返回空
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;
}
欢迎讨论指点,转载请注明。