HashMap源码解析

HashMap源码解析

简介

HashMap是一个根据键值(Key)而直接访问在内存存储位置的数据结构。也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中的一个位置来访问记录,这加快了查找速度。这个映射函数称作散列函数,存放记录的数组称作散列表。

HashMap继承了AbstractMap,实现了Map、Cloneable、Serializable接口。

1
2
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable{}

HashMap很奇怪,明明继承了AbstractMap(AbstractMap实现了Map接口),却又自己实现了Map接口。这个原因可以参考StackOverflow上的这个回答

实现了Cloneable接口,重写了clone方法

实现Serializable接口,支持序列化和反序列化

实现逻辑

HashMap使用Node节点和Node数组来实现逻辑的。

主要属性

  • DEFAULT_INITIAL_CAPACITY:HashMap初始化大小,默认为16
  • DEFAULT_LOAD_FACTOR:HashMap初始化负载因子,默认0.75
  • TREEIFY_THRESHOLD:HashMap冲突链表转为红黑树的阈值,默认是8
  • UNTREEIFY_THRESHOLD:HashMap冲突红黑树转为链表的阈值,默认是6
  • MIN_TREEIFY_CAPACITY:HashMap的数量阈值,到达64之后才允许将冲突链表转为红黑树
  • table:存放数据的Node数组
  • size:HashMap的大小
  • modCount:用于快速失败的计数

主要函数

构造函数

无参构造函数

使用默认参数,创建HashMap

1
2
3
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

有参构造函数(指定大小)

1
2
3
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

HashMap会生成一个最接近于指定大小的2的N次幂大小的HashMap.比如,指定大小为11,那么HashMap会生成一个大小为16的HashMap。

有参构造函数(指定大小和负载因子)

同上,支持指定负载因子。大小也会被扩大为最接近它的2的N次幂大小。

1
2
3
4
5
6
7
8
9
10
11
12
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}

有参构造函数(指定容器)

1
2
3
4
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}

size()

1
2
3
public boolean isEmpty() {
return size == 0;
}

isEmpty()

1
2
3
public boolean isEmpty() {
return size == 0;
}

get(Object)

1
2
3
4
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

get方法调用了getNode方法

getNode()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
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) {
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;
}
  1. 首先判断Node数组是不是空的
  2. 再判断头结点的Hash值和key是否相等,相等的话直接返回头结点
  3. 如果当前节点是树节点,在红黑树中找
  4. 如果不是树节点,则在链表中找
  5. 如果都找不到,返回null

containsKey(Object)

1
2
3
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}

判断getNode方法返回的对应值是否为null

put(Object, Object)

1
2
3
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

put方法调用了内部方法oytVal来插入数据

putVal方法

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
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;
}
  1. 首先判断当前Node数组是否为空,是的话,调用resize方法初始化数组
  2. 通过Hash值,找到数据在数组中对应的索引值,如果当前索引值处数据位null,就新生成一个节点插入
  3. 定位到Hash冲突的节点
  4. 如果当前节点是树节点,加入到树中
  5. 如果当前节点是链表节点,在链表尾新增一个节点
  6. 如果新增节点之后,链表长度超过阈值,则转为红黑树
  7. 如果当前key已经在Map中了,那么就在29行开始处,更新已有的值
  8. 接着判断当前大小是否超过阈值,是的话,哈希表扩容

resize方法

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
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 不是首次插入
if (oldCap > 0) {
// 如果当前容量已经超过最大容量,那么直接将阈值设置为Integer.MAX_VALUE
// 不再扩容,直接返回原Node数组
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 否则,HashMap大小扩容两倍
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"})
// 生成一个2倍于原数组大小的Node数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 将原Node数组里的Node重新hash
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
// 如果当前索引有数值
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 如果只有一个头结点,直接插入新数组
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 如果是树节点
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
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;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
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;
}

remove(Object)

1
2
3
4
5
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}

调用方法removeNode实现移除逻辑

removeNode()

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
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);
}
}
// 如果找的了对应的Node结点
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;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
  1. 首先,找到对应符合条件的Node
  2. 移除

clear()

1
2
3
4
5
6
7
8
9
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
  1. 将size置为0
  2. 遍历node数组,每个值都置为null
0%