HashMap部分源码简析

有参构造

HashMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
//容量、负载因子
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;
//确保容量是2的整数次幂
this.threshold = tableSizeFor(initialCapacity);
}

tableSizeFor

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Returns a power of two size for the given target capacity.
*/
//返回大于输入参数且最近的2的整数次幂的数。比如10,则返回16
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;
}

put方法

put

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
//调用hash(Object key)函数获取它的hashcode高16位与低16位异或后的值
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

hash

1
2
3
4
5
6
//返回hashcode高16位与低16位异或后的值
//如果key为null,直接返回0,即key为null放置在数组'0'下标处
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

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
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
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果table数组未初始化或长度为0,则进行扩容
if ((tab = table) == null || (n = tab.length) == 0)
//扩容
n = (tab = resize()).length;
//将hash值与数组长度-1做与运算获得所在下标
//即(hash & (table.length-1)) 等价于 hash % table.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) {
//如果遍历到链表尾部仍没找到key相等的结点,则在尾部插入,并结束循环
if ((e = p.next) == null) {
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;
}
}
//如果在链表中找到key相等的结点,则返回旧值
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;
}

resize方法

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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
//保存当前的table
Node<K,V>[] oldTab = table;
//保存当前table的容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//保存当前的阈值
int oldThr = threshold;
//新容量,新阈值
int newCap, newThr = 0;
//如果当前容量大于0
if (oldCap > 0) {
//如果当前容量大于最大容量(static final int MAXIMUM_CAPACITY = 1 << 30;)
if (oldCap >= MAXIMUM_CAPACITY) {
//就将阈值设为最大整型
threshold = Integer.MAX_VALUE;
return oldTab;
}
//将容量翻倍后小于最大容量 并且 当前容量大于等于默认容量(static final int DEFAULT_INITIAL_CAPACITY = 1 << 4 就是16)
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//新阈值翻倍
newThr = oldThr << 1; // double threshold
}
//当前容量等于0,阈值大于0
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//当前容量和当前阈值都为0
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//新阈值等于0
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;
//旧table不为null
if (oldTab != null) {
//遍历整个hashmap数组
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//如果某一下标处元素不为null
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//只有一个结点
if (e.next == null)
//直接放入新table中
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);
//两条新链表相隔一个oldCap这么远
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
//返回新table
return newTab;
}