一、HashMap概述
HashMap是Java集合框架中最重要的数据结构之一,它基于哈希表实现,提供了高效的键值对存储和检索功能。在JDK1.8中,HashMap的实现经历了重大改进,提升了性能并解决了某些极端情况下的效率问题。
二、JDK1.8前的HashMap实现
1. 数据结构
在JDK1.8之前,HashMap采用"数组+链表"的结构:
// JDK1.7的HashMap核心结构
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next; // 链表指针
int hash;
// 构造方法和其它代码...
}
transient Entry<K,V>[] table; // 哈希表数组
2. 插入元素
// JDK1.7的put方法简化版
public V put(K key, V value) {
if (key == null)
return putForNullKey(value); // 处理null键
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length); // 计算数组下标
// 遍历链表检查是否已存在
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
return oldValue;
}
}
// 不存在则添加新Entry
addEntry(hash, key, value, i);
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e); // 头插法
if (size++ >= threshold)
resize(2 * table.length); // 扩容
}
3. 哈希冲突解决
JDK1.7采用链表法解决哈希冲突,新元素总是插入链表头部(头插法)。这种实现可能导致多线程环境下出现环形链表问题。
4. 删除元素
// JDK1.7的remove方法简化版
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
final Entry<K,V> removeEntryForKey(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
while (e != null) {
Entry<K,V> next = e.next;
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
if (prev == e)
table[i] = next;
else
prev.next = next;
return e;
}
prev = e;
e = next;
}
return e;
}
三、JDK1.8的HashMap实现
1. 数据结构改进
JDK1.8引入"数组+链表+红黑树"的混合结构:
// JDK1.8的Node定义
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next; // 链表指针
// 构造方法和其它代码...
}
// 红黑树节点
static final 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; // 颜色标记
// 构造方法和其它代码...
}
transient Node<K,V>[] table; // 哈希表数组
2. 插入元素优化
// JDK1.8的put方法简化版
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 存在则更新值
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
return oldValue;
}
}
// 检查扩容
if (++size > threshold)
resize();
return null;
}
3. 哈希冲突解决改进
JDK1.8仍然使用链表法解决冲突,但有三大改进:
- 链表插入改为尾插法,避免多线程环境下产生环形链表
- 当链表长度超过阈值(默认为8)时,链表转换为红黑树
- 当红黑树节点数小于阈值(默认为6)时,红黑树退化为链表
4. 删除元素优化
// JDK1.8的remove方法简化版
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
// 检查第一个节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
// 如果是树节点
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
// 遍历链表
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 删除节点
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
// 树节点删除
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
// 链表头节点删除
else if (node == p)
tab[index] = node.next;
// 链表中间节点删除
else
p.next = node.next;
return node;
}
}
return null;
}
四、JDK1.8的重要优化点
- 红黑树引入:当链表长度超过8时转为红黑树,查询时间复杂度从O(n)降为O(logn)
- 扩容优化:JDK1.8在扩容时不需要重新计算hash,而是通过高位运算确定新位置
- 插入方式:从头插法改为尾插法,避免多线程环境下产生环形链表
- hash算法简化:减少了哈希冲突的可能性
// JDK1.8的hash算法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
五、总结对比
|
特性 |
JDK1.7及之前 |
JDK1.8及之后 |
|
数据结构 |
数组+链表 |
数组+链表+红黑树 |
|
插入方式 |
头插法 |
尾插法 |
|
哈希冲突解决 |
纯链表 |
链表长度>8转红黑树,<6转回链表 |
|
多线程安全性 |
可能产生环形链表 |
仍非线程安全但不会产生环形链表 |
|
查询效率 |
O(n)最坏情况 |
O(logn)最坏情况 |
|
扩容机制 |
重新计算hash |
利用高位运算优化 |
HashMap在JDK1.8中的改进显著提升了性能,特别是在哈希冲突严重的情况下,通过引入红黑树保证了较好的查询效率。尾插法的使用也解决了多线程环境下可能出现的环形链表问题,但是依然存在线程不安全,在多线程环境下应当优先使用ConcurrentHashMap!!!!!
359

被折叠的 条评论
为什么被折叠?



