HashMap 原理及源码分析
1. 存储结构
HashMap 内部是由 Node
类型的数组实现的。Node
包含着键值对,内部有四个字段,从 next
字段我们可以看出,Node
是一个链表。即数组的每一个位置被当作一个桶,每个桶存储一个链表。HashMap 使用拉链法来解决冲突,同一个桶中存放 hashcode 与数组长度取模运算结果相同的 Node
。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, 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; }
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;
}
}
2. 索引计算
在 HashMap 中,node
在数组中的索引根据 key 的哈希值与数组长度取模运算得到。
如下为 HashMap 中 putVal 方法(put方法的实际执行过程),
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab