哈希類集合的三個基本存儲概念:
- table,存儲所有節點資料的數組
- slot 哈希槽,即 table[i] 的位置
- bucket 哈希桶,即 table[i] 上所有元素形成的表或者樹的集合
存儲所有節點的table數組
transient Node<K,V>[] table;
描述一個hash節點資訊:
static class Node<K,V> implements Map.Entry<K,V> {
// hash值
final int hash;
// 鍵
final K key;
// 值
V value;
// 下一個節點
HashMap.Node<K,V> next;
Node(int hash, K key, V value, HashMap.Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
// 計算hashcode
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
// 相等性判斷
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}