HashMap 源码分析

特征

  • 根据键的 hascode 值存储数据,可直接定位值,具有很快的数据访问数组
  • 遍历的顺序不确定
  • 最多允许一条 null 键,允许多条记录的键为 null
  • 非线程安全
    可使用 Collections.synchronizedMap 使 HashMap 具有线程安全的能力 或 ConcurrentHashMap

底层结构

底层结构采用了数组,而数组的每一个元素都是多个 Node 构成的链表,当数组超过 threshold 时,数组将会扩容。

数组中的每一个都相当于一个单向链表,key 通过 hash() 后,相同的键值对会加入到链表中,当桶中的数过多时(链表长度 > 8),将会转化为 红黑树,相比与Jdk 1.7, Jdk 1.8 中当链表过长时,链表转化为红黑树,在维护红黑树时,最坏情况下查找的时间复杂度为 O(log n),比起单链表的 O(1) ~ O(n), 时间复杂度降低了,但所需要维护的空间占用却更多。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 哈希数组桶,根据 key 的 hashCode 通过 hash() 得到数组下标
transient Node<K,V>[] table;

// 结构最大数据量,即 Node 的最大值,由 loadFactor(o.75) * length(16) 得到
int threshold;

// 负载因子
final float loadFactor;

// 桶中的 Node 节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}

哈希映射 & 表大小

hash() — 取得 key 的 hashCode 值,依次进行 高位运算,取模运算

tableSizeFor() — 返回大于参数且最接近 2 的整数幂的数值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 取得hashCode 的值
* 右位移 16 位,正好是 32bit 的一半,将高半位和低半位做异或
* 混合原始哈希码的高位和地位,以此加大随机性
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}


// 将二进制转化为1,找出最大的 2^n的值
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

扩容

扩容机制实际上就是使用一个更大的数组去 代替 原来的数组,如果原来的数组中存在红黑树 或 链表,则需要把结构重新调整。
对于链表而言, 设计者省略了重新计算新容量下 key 的 hash 值,采用将 hash 值与原容量进行与操作,得到不同的扩展区,两个扩展区分为两条链表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
final Node<K,V>[] resize() {
// 记录oldTab, oldCap, oldThr 等数据
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;

// 当容量大到不能调整时,采用Integer.MAX_VALUE 作为最大容量 threshold
// 否则,将采用位运算,将 oldCap 和 oldThr 扩展为原来的两倍
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}

// 尚未分配空间,初始化
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;

// 重新分配空间
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {

// 循环遍历桶
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;

//首元素赋予 null,便于GC
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;

// 桶中的结构是 红黑树,采用 split()调整结构
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

// 桶中结构为单链表
// 容量增加了,散列时使用的位扩展了一位,通过新扩展为0 1区分
else { // preserve order

// 分为两条链表,在尾部插入新节点
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;

// 新扩展位为0
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}

// 新扩展位为1
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);

// 将头节点放入数组桶中
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

存入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;

// 判断空桶,resize()重新建桶
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;

// 首节点为null, 新建节点Node
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;

// 桶中结构为红黑树,调用红黑树的 putTreeVal()
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) {

// 以此存入节点,当链表总数大于8时,转化为红黑树
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}

//key已在链表中
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;

// 当容量大于 threshold, 进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 查找对应key 的值
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

// 查找是否存在 key 对应的值
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}

// 查找的具体操作
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

// table不为空 && 首节点不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {

// 首节点命中,直接返回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;

// 非首节点的情况下
if ((e = first.next) != null) {

// 通过红黑树结构查找,调用 getTreeNode()
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);

// 链表顺序查找
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}

删除

删除的操作与查找差不多,都是要通过key找到对应的节点,再删除节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// 删除指定key的值
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;

// 首节点命中,赋值node便于删除
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);

// 首节点删除,将首节点的next赋值为首节点
else if (node == p)
tab[index] = node.next;

// 链表删除,节点的next 指向删除节点的 next
else
p.next = node.next;

// 修改计数, 长度减一, 返回删除节点
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}