java数据结构-hashmap
1. hashmap数据结构
没有哈希冲突时,为数组,支持动态扩容
哈希冲突时,分为两种情况:
1.当冲突长度小于8或数组长度小于64(min_treeify_capacity默认值为64)时,为数组+链表(node)
2.当冲突长度大于8时,为数组+红黑树/链表(treenode)。
红黑树用于快速查找,链表用于遍历。
2. 红黑树
hashmap中的treenode是红黑树的实现。
treenode几个方法
1. 左旋转
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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; } |
实现效果如图
2. 右旋转
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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; } |
实现效果如图
3. 插入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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); } } } } } } |
实现效果如下:
以上所述是小编给大家介绍的java数据结构-hashmap详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.cnblogs.com/huiyao/p/10549752.html