Map
接口的实现类(如HashMap
、TreeMap
等)底层使用哈希表结构来存储键值对,使用链表和红黑树来解决哈希冲突。java 8
开始,HashMap
哈希冲突的解决采用链表 + 红黑树的方案。当某个槽位的链表长度达到8,这个槽位的链表会转化为红黑树。
底层如何存储数据
以HashMap为例,在这些数据结构中,键值对被存储在Map.Entry对象中,Map.Entry对象包含键、值以及指向下一个Map.Entry对象的引用(用于处理哈希冲突)。
HashMap中Map.Entry对象源码(静态内部类Node实现了Map.Entry接口)
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;
return o instanceof Map.Entry<?, ?> e
&& Objects.equals(key, e.getKey())
&& Objects.equals(value, e.getValue());
}
}
Map.Entry对象被存储在一个数组中,这个数组被称为table。当插入一个新的键值对时,HashMap
会根据键的哈希值计算出数组中的下标,然后将新的Entry
对象存储在这个下标位置。如果发生哈希冲突,HashMap
会使用链表或红黑树来存储冲突的Entry
对象。
源码
table为全局变量。
transient Node<K,V>[] table;
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}