```
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;
//比较根节点的 hash 值,dir 猜测是决定节点插入时应该插到左子节点还是右子节点
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
//如果根节点的 key 和要插入节点的 key 相同,直接返回根节点
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
//根节点的 key 和要插入的 key 不同,开始比较根节点的左右子节点
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))
//找到相同的 key,将节点返回
return q;
}
//这里记录下 dir,可能是决定为了如果从子节点也找不到接下来创建新的节点插入到左边还是右边
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;
}
}
}
```
```
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;
? //比较根节点的 hash 值,dir 猜测是决定节点插入时应该插到左子节点还是右子节点
? if ((ph = p.hash) > h)
? dir = -1;
? else if (ph < h)
? dir = 1;
? else if ((pk = p.key) == k || (k != null && k.equals(pk)))
? //如果根节点的 key 和要插入节点的 key 相同,直接返回根节点
? return p;
? else if ((kc == null &&
? (kc = comparableClassFor(k)) == null) ||
? (dir = compareComparables(kc, k, pk)) == 0) {
? //根节点的 key 和要插入的 key 不同,开始比较根节点的左右子节点
? 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))
? //找到相同的 key,将节点返回
? return q;
? }
? //这里记录下 dir,可能是决定为了如果从子节点也找不到接下来创建新的节点插入到左边还是右边
? 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;
? }
? }
? }
```
不知道分析的对不对~希望大佬一起交流