HashMap
是 Java 集合框架中最常用的数据结构之一,基于哈希表(Hash Table)实现。它以键值对(Key-Value)存储数据,允许 null
键和 null
值,且无序。
null
键和 null
值16
,负载因子 0.75
Map map = new HashMap();
map.put("Java", 1);
map.put("Python", 2);
System.out.println(map.get("Java")); // 1
在 JDK 1.7 及之前,HashMap
采用 数组 + 链表 实现:
table[0] → (key1, value1) → (key2, value2) → (key3, value3) → null
table[1] → (key4, value4) → null
table[2] → (key5, value5) → null
...
JDK 1.8 进行了优化:
table[0] → (key1, value1) → (key2, value2) → 红黑树
table[1] → (key3, value3) → null
table[2] → (key4, value4) → null
put(K key, V value)
方法put()
方法用于向 HashMap
添加键值对,底层步骤如下:
hash(key)
方法,计算 key
在数组中的索引。key
对应的数组位置 table[index]
。threshold
(容量 * 负载因子),触发 resize() 扩容。源码分析:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
hash(key)
计算键的哈希值。putVal()
负责存储键值对。hash()
计算哈希值static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
解释:
key.hashCode()
获取哈希码。^
),减少哈希冲突。resize()
扩容机制当 HashMap
的元素数量超过阈值(默认 0.75 * capacity
),会进行扩容:
newCapacity = oldCapacity * 2
)。源码:
void resize(int newCapacity) {
Node[] oldTable = table;
int oldCapacity = oldTable.length;
int newThreshold = (int)(newCapacity * loadFactor);
table = new Node[newCapacity];
for (Node e : oldTable) {
if (e != null) {
int newIndex = e.hash & (newCapacity - 1);
table[newIndex] = e;
}
}
}
版本 | 结构 | 主要优化 |
---|---|---|
JDK 1.7 | 数组 + 链表 | 头插法(导致死循环) |
JDK 1.8 | 数组 + 链表 + 红黑树 | 1. 采用 尾插法 避免死循环 2. 长链表转换为 红黑树 |
resize()
)。ConcurrentHashMap
:推荐使用,线程安全,性能高。Collections.synchronizedMap(new HashMap())
:使用同步包装类。示例:
Map syncMap = Collections.synchronizedMap(new HashMap());
hash & (length - 1)
而不是 hash % length
?A:&
运算比 %
更高效,length
为 2 的幂时,hash & (length - 1)
能保证均匀分布。
A:当元素个数 超过 capacity * loadFactor
(默认 16 * 0.75 = 12
)时。
A:
A:
0.75
,超过 capacity * 0.75
时扩容。ConcurrentHashMap
代替 HashMap
。参与评论
手机查看
返回顶部