Java HashMap removeNode 方法 分析
原始碼分析倉庫 https://github.com/HANXU2018/JavaSourcesLearn

remove 原始碼
remove 呼叫的 removeNode() 方法
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
// 洗掉呼叫 removeNode
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
removeNode 原始碼
卡主我的 部分就是 node 和 P 的關系 沒有搞懂
p 是 node 的前一個節點 相當于 pre
如果 node 就一個 node == p
/**
* Implements Map.remove and related methods.
* 實作了 Map 的 remove 抽象方法
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
// 洗掉元素的 hash 值 鍵key 值value 只洗掉 value 一樣的值 matchValue 可不可以并行同時洗掉 movable
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
// 還是那幾個 變數
// tab 哈希表
// p 是當前 node
// n 是哈希表代銷
// index 當前位置
Node<K,V>[] tab; Node<K,V> p; int n, index;
// 過濾又賦值
//
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
// node 找的 node
// e 下一個節點
// K key
// V value
// 這一大塊 都是 查找值的位置 回傳 node
Node<K,V> node = null, e; K k; V v;
// key 和 hash 相等 node 就是要找的
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
// 是不是 紅黑樹 紅黑樹呼叫自己的getTreeNode介面
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
// 不是紅黑樹 普通鏈表進行遍歷
do {
// 判斷 e 是不是 key 和 hash 都相等
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 這回 node 應該 找到了 一個簡單的過濾 值是不是相等或者 需不需要判斷值
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
// 紅黑樹的操作是 額外的價格
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p) // 普通刪就直接進入下一個
tab[index] = node.next;
else
p.next = node.next;
// P 代表上一個 節點 如果 node == p 代表就一個節點 else 就是 鏈表中的節點 洗掉 node 就 p 的下一個 跳過 node
// he number of times this HashMap has been structurally modified
++modCount;// 進行了 結構操作
// 元素個數減一了
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/272613.html
標籤:其他
上一篇:NTFS安全權限
