博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 8 HashMap中的TreeNode.putTreeVal方法分析
阅读量:6975 次
发布时间:2019-06-27

本文共 6893 字,大约阅读时间需要 22 分钟。

举例一个入口,利用一个Map构造HashMap时

/**     * Constructs a new HashMap with the same mappings as the     * specified Map.  The HashMap is created with     * default load factor (0.75) and an initial capacity sufficient to     * hold the mappings in the specified Map.     *     * @param   m the map whose mappings are to be placed in this map     * @throws  NullPointerException if the specified map is null     */    public HashMap(Map
m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }

然后就是调用putMapEntries方法,第二个参数其实可以看作细节,个人认为它和HashMap的子类LinkedHashMap有关,evict是逐出的意思,如果基于LinkedHashMap实现LRU缓存的话,这个evict参数正好就用上了。

/**     * Implements Map.putAll and Map constructor     *     * @param m the map     * @param evict false when initially constructing this map, else     * true (relayed to method afterNodeInsertion).     */    final void putMapEntries(Map
m, boolean evict) { int s = m.size(); if (s > 0) { if (table == null) { // pre-size float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); if (t > threshold) threshold = tableSizeFor(t); } else if (s > threshold) resize(); for (Map.Entry
e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } }

可以看到在for循环中遍历旧的entrySet视图,然后将一个个的key-value对放入新构造的HashMap中,

for (Map.Entry
e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); }

展开putVal(hash(key), key, value, false, evict);

/**     * Implements Map.put and related methods     *     * @param hash hash for key     * @param key the key     * @param value the value to put     * @param onlyIfAbsent if true, don't change existing value     * @param evict if false, the table is in creation mode.     * @return previous value, or null if none     */    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,                   boolean evict) {        Node
[] tab; Node
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
e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode
)p).putTreeVal(this, tab, hash, key, value); 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; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }

通过hash(key)定位到HashMap中tab数组的索引,如果这个数组元素的头节点正好是TreeNode类型,那么就将执行

e = ((TreeNode
)p).putTreeVal(this, tab, hash, key, value);

此时this是HashMap自身。

putTreeVal考虑两大情况,
1)key已经存在这个红黑树中当中了,就直接放回对应的那个节点;
2)从红黑树的root节点开始遍历,定位到要插入的叶子节点,插入新节点;
putTreeVal除了要维护红黑树的平衡外(可以参考TreeMap源码),还需要维护节点之间的前后关系,这里似乎同时是在维护双向链表关系。

/**         * Tree version of putVal.         */        final TreeNode
putTreeVal(HashMap
map, Node
[] tab, int h, K k, V v) { Class
kc = null; boolean searched = false; TreeNode
root = (parent != null) ? root() : this; for (TreeNode
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 && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) { if (!searched) { TreeNode
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
xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { Node
xpn = xp.next; TreeNode
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
)xpn).prev = x; moveRootToFront(tab, balanceInsertion(root, x)); return null; } } }

下面重点分析putTreeVal方法

1 首先找到root节点,

TreeNode
root = (parent != null) ? root() : this;

这里的this是指TreeNode自己,从某个节点一直往上溯,直到parent==null的情况

2 递归遍历root
判断节点之间的hash大小,如果hash值相等采用key比较等
然后采用左子树或者右子树,继续遍历
(关于key值大小的比较算是细节的地方,这里暂且代入String类型的key解读源码以图整体思路流畅)
3 如果遍历到了叶子节点
比如上一步采用左子树,而左子树刚好是叶子节点,p == null
此时递归遍历结束

if ((p = (dir <= 0) ? p.left : p.right) == null) {                    Node
xpn = xp.next; TreeNode
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
)xpn).prev = x; moveRootToFront(tab, balanceInsertion(root, x)); return null; }

xp是叶子节点的父节点,这个节点不是null,叶子节点p一定是null

新增一个节点x,next指向原来父节点的.next,x就是新增的叶子节点
1) 处理红黑树的关系
父节点xp和叶子节点x的关系,落在左子树还是右子树;
x的parent指向父节点xp x.parent = xp
最后保持红黑树平衡
2)处理双向链表的关系
类似于在xp-->xpn(xp.next)中间插入新的节点x,

x = map.newTreeNode(h, k, v, xpn);x.prev = xp//如果xpn不是null,则处理xpn的prev((TreeNode
)xpn).prev = x;

图示

clipboard.png

clipboard.png

3) 保持红黑树平衡

moveRootToFront(tab, balanceInsertion(root, x));

转载地址:http://mcrsl.baihongyu.com/

你可能感兴趣的文章
Entity Framework DBFirst尝试
查看>>
pojBuy Tickets2828线段树或者树状数组(队列中倒序插队)
查看>>
【BZOJ】1600: [Usaco2008 Oct]建造栅栏(dp)
查看>>
linux下启动oracle
查看>>
【原创】开源Math.NET基础数学类库使用(02)矩阵向量计算
查看>>
SqlHelper
查看>>
前端画面-下拉后滚动
查看>>
golang使用http client发起get和post请求示例
查看>>
remoting生命周期
查看>>
[zz]malloc()和calloc()
查看>>
Sylius – 100% 免费和开源的电子商务解决方案
查看>>
单片机系列学习
查看>>
BZOJ3571 : [Hnoi2014]画框
查看>>
读枯燥的技术书时怎么集中精神?
查看>>
【github】github 使用教程初级版
查看>>
iOS 依据文本内容为TextView动态定义高度
查看>>
信号练习
查看>>
UML类图几种关系的总结
查看>>
JavaScript学习笔记——流程控制
查看>>
CCF系列之ISBN号码(201312-2)
查看>>