Skip to content

Instantly share code, notes, and snippets.

@ntub46010
Last active October 18, 2023 07:43
// 以下改寫自原始碼,較好閱讀
Node<K,V> getNode(Object key) {
Node<K,V>[] tab = this.table;
if (tab != null || tab.length <= 0) return null;
// 計算 key 的新 hash
int hash = hash(key);
// 計算餘數,得出 bucket 的位置
int bucketIndex = (tab.length - 1) & hash;
// 取得 bucket 中第一個節點
Node<K,V> first = tab[bucketIndex];
if (first == null) return null;
// ...
}
// 以下改寫自原始碼,較好閱讀
int hash(Object key) {
if (key == null) return 0;
// 步驟一:計算 key 的原始 hash code
int h = key.hashCode();
// 步驟二:取得高位的 16 位元
int higherBits = h >>> 16;
// 步驟三:兩者做 XOR 位元運算
return h ^ higherBits;
}
class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
// ...
}
public class HashMap<K,V> implements ... {
Node<K,V>[] table;
// ...
}
// 父父類別有實作 Map.Entry<K,V>
class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent;
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev;
boolean red;
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment