1.HashMap介绍

1.1 HashMap底层存储结构

HashMap最早出现在JDK1.2中,底层基于散列算法实现。HashMap 允许 null 键和 null 值,是非线程安全类,在多线程环境下可能会存在问题。

1.8版本的HashMap底层存储结构:

数组+链表+红黑树

1.2 HashMap类的定义

先来看看HashMap类的定义:

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

从中我们可以了解到:

  • HashMap<K,V>HashMap是以key-value形式存储数据的。

  • extends AbstractMap<K,V>:继承了AbstractMap,大大减少了实现Map接口时需要的工作量。

  • implements Map<K,V>:实现了Map,提供了所有可选的Map操作。

  • implements Cloneable:表明其可以调用clone()方法来返回实例的field-for-field拷贝。

  • implements Serializable:表明该类是可以序列化的。

1.3 put()数据原理分析

1.4常见名词解释

  1. hashmap的底层数据结构名为table的数组,是一个Node数组

  2. table数组中的每个元素是一个Node元素(但是这个Node元素可能指向下一个Node元素从而形成链表),table数组的每个位置称为桶,比如talbe[0] 称为一个桶,也可以称为一个bin

2.源码

2.1 核心属性分析

静态常量

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
/**
* The default initial capacity - MUST be a power of two.
* 默认的初始容量,必须是二的次方
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*
* 最大容量,当通过构造函数隐式指定了一个大于MAXIMUM_CAPACITY的时候使用
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
* The load factor used when none specified in constructor.
* 加载因子,当构造函数没有指定加载因子的时候的默认值的时候使用
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*
* TREEIFY_THRESHOLD为当一个bin从list转化为tree的阈值,当一个bin中元素的总元素最低超过这个值的时候,bin才被转化为tree;
* 为了满足转化为简单bin时的要求,TREEIFY_THRESHOLD必须比2大而且比8要小
*/
static final int TREEIFY_THRESHOLD = 8;

/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*
* bin反tree化时的最大值,应该比TREEIFY_THRESHOLD要小,
* 为了在移除元素的时候能检测到移除动作,UNTREEIFY_THRESHOLD必须至少为6
*/
static final int UNTREEIFY_THRESHOLD = 6;

/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*
* 树化的另外一个阈值,table的长度(注意不是bin的长度)的最小得为64。为了避免扩容和树型结构化阈值之间的冲突,MIN_TREEIFY_CAPACITY 应该最小是 4 * TREEIFY_THRESHOLD
*/
static final int MIN_TREEIFY_CAPACITY = 64;


成员变量

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
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*
* table,第一次被使用的时候才进行加载
*/
transient Node<K,V>[] table;

/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
* 键值对缓存,它们的映射关系集合保存在entrySet中。即使Key在外部修改导致hashCode变化,缓存中还可以找到映射关系
*/
transient Set<Map.Entry<K,V>> entrySet;

/**
* The number of key-value mappings contained in this map.
* table中 key-value 元素的个数
*/
transient int size;

/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*
* HashMap在结构上被修改的次数,结构上被修改是指那些改变HashMap中映射的数量或者以其他方式修改其内部结构的次数(例如,rehash)。
* 此字段用于使HashMap集合视图上的迭代器快速失败。
*/
transient int modCount;

/**
* The next size value at which to resize (capacity * load factor).
*
* 下一次resize扩容阈值,当前table中的元素超过此值时,触发扩容
* threshold = capacity * load factor
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.(???????))
int threshold;

/**
* The load factor for the hash table.
* 负载因子
* @serial
*/
final float loadFactor;

这里讲下负载因子:

对于 HashMap 来说,负载因子是一个很重要的参数,该参数反应了 HashMap 桶数组的使用情况。通过调节负载因子,可使 HashMap 时间和空间复杂度上有不同的表现。

当我们调低负载因子时,HashMap 所能容纳的键值对数量变少。扩容时,重新将键值对存储新的桶数组里,键的键之间产生的碰撞会下降,链表长度变短。此时,HashMap 的增删改查等操作的效率将会变高,这里是典型的拿空间换时间。

相反,如果增加负载因子(负载因子可以大于1),HashMap 所能容纳的键值对数量变多,空间利用率高,但碰撞率也高。这意味着链表长度变长,效率也随之降低,这种情况是拿时间换空间。至于负载因子怎么调节,这个看使用场景了。

一般情况下,我们用默认值就可以了。大多数情况下0.75在时间跟空间代价上达到了平衡所以不建议修改。

2.2 构造方法分析

只看构造方法中参数最多的一个即可,其他的都是调用这个构造方法:

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
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);
}

/**
* Returns a power of two size for the given target capacity.
*
* 1.返回一个大于等于当前值cap的一个的数字,并且这个数字一定是2的次方数
* 假如cap为10,那么n= 9 = 0b1001
* 0b1001 | 0b0100 = 0b1101
* 0b1101 | 0b0011 = 0b1111
* 0b1111 | 0b0011 = 0b1111
* ......
* .....
* n = 0b1111 = 15
*
* 2.这里的cap必须要减1,如果不减,并且如果传入的cap为16,那么算出来的值为32
*
* 3.这个方法就是为了把最高位1的后面都变为1
* 0001 1101 1100 -> 0001 1111 1111 -> +1 -> 0010 1111 1111
*/
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;
}

2.3 put方法分析

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
/**
* @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 key, or
* null if there was no mapping for key.
* (A null return can also indicate that the map
* previously associated null with key.)
* 返回先前key对应的value值(如果value为null,也返回null),如果先前不存在这个key,那么返回的就是null;
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/
* 在往haspmap中插入一个元素的时候,由元素的hashcode经过一个扰动函数之后再与table的长度进行与运算才找到插入位置,下面的这个hash()方法就是所谓的扰动函数
* 作用:让key的hashCode值的高16位参与运算,hash()方法返回的值的低十六位是有hashCode的高低16位共同的特征的
* 举例
* hashCode = 0b 0010 0101 1010 1100 0011 1111 0010 1110
*
* 0b 0010 0101 1010 1100 0011 1111 0010 1110 ^
* 0b 0000 0000 0000 0000 0010 0101 1010 1100
* 0b 0010 0101 1010 1100 0001 1010 1000 0010
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

让高16位参与运算的原因,说明一下:当数组的长度很短时,只有低位数的hashcode值能参与运算。而让高16位参与运算可以更好的均匀散列,减少碰撞,进一步降低hash冲突的几率。并且使得高16位和低16位的信息都被保留了。
然后有不少博客提到了因为int是4个字节,所以右移16位。原因大家可以打开hashmap的源码,找到hash方法,按住ctrl点击方法里的hashcode,跳转到Object类,然后可以看到hashcode的数据类型是int。int为4个字节,1个字节8个比特位,就是32个比特位,所以16很可能是因为32对半的结果,也就是让高的那一半也来参与运算。

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
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
// tab表示当前hashmap的table
// p表示table的元素
// n表示散列表的长度
// i表示路由寻址结果
Node<K,V>[] tab; Node<K,V> p; int n, i;

// 延迟初始化逻辑,第一次调用putval()方法的时候才进行初始化hashmap中最耗内存的talbe
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;

// 1.最简单的一种情况,寻找到的桶位,刚好是null,这个时候直接构建Node节点放进去就行了
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);


else {
// e,如果key不为null,并且找到了当前要插入的key一致的node元素,就保存在e中
// k表示一个临时的key
Node<K,V> e; K k;

// 2.表示该桶位中的第一个元素与你当前插入的node元素的key一致,表示后序要进行替换操作
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;

// 3.表示当前桶位已经树化了
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

// 4.当前捅位是一个链表
else {
for (int binCount = 0; ; ++binCount) {
// 4.1 迭代到最后一个元素了也没有找到要插入的key一致的node
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}

// 4.1 找到了与要插入的key一致的node元素
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 如果找到了与要插入的key一致的node元素,那么进行替换
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// nodeCount表示散列表table结构的修改次数,替换Node元素的value不算
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

注意:

  1. HashMap的hash算法(hash()方法)。
  2. (n - 1) & hash等价于对 length 取余

2.4 resize方法分析

在 HashMap 中,桶数组的长度均是2的幂,阈值大小为桶数组长度与负载因子的乘积。当 HashMap 中的键值对数量超过阈值时,进行扩容。

举个例子:

当在table长度位16中的元素移到table长度位32的table中的时候;我们可以知道,原来在15这个槽位的元素的hash()值的后四位一定是1111(因为跟1111即table长度-1 进行与运算得到了1111)。所以所以当table长度变为32的时候,原来在15这个槽位的元素要么还在15这个槽位,要么在31这个操作(因为原来15这个槽位的元素后五位一定是11111或者01111,跟 11111即table新长度-1 进行与运算一定得到 01111或者11111)

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
110
111
112
113
114
115
116
/**
* 对table进行初始化或者扩容。
* 如果table为null,则对table进行初始化
* 如果对table扩容,因为每次扩容都是翻倍,与原来计算(n-1)&hash的结果相比,节点要么就在原来的位置,要么就被分配到“原位置+旧容量”这个位置。
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// oldCap表示扩容之前table数组的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// oldThr表示本次扩容之前的阈值,触发本次扩容操作的阈值
int oldThr = threshold;
// newCap:表示扩容之后table数组的大小; newThr表示扩容之后,下次出发扩容的条件
int newCap, newThr = 0;
//===================给newCap和newThr赋值start=============================
// oldCap大于零,说明之前已经初始化过了(hashmap中的散列表不是null),要进行正常的扩容操作
if (oldCap > 0) {
// 已经最大值了,不再扩容了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// (1)进行翻倍扩容(假如旧的oldCap为8, < DEFAULT_INITIAL_CAPACITY,那么此条件不成立newThr将不会赋值)
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// (2)
// oldCap == 0(说明hashmap中的散列表是null)且oldThr > 0 ;下面几种情况都会出现oldCap == 0,oldThr > 0
// 1.public HashMap(int initialCapacity);
// 2.public HashMap(Map<? extends K, ? extends V> m);并且这个map有数据
// 3.public HashMap(int initialCapacity, float loadFactor);
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// oldCap == 0, oldThr == 0
// public HashMap();
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}

// 对应上面(1)不成立或者(2)成立的情况
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//===================给newCap和newThr赋值end=============================
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;
// 头结点不为空
if ((e = oldTab[j]) != null) {
// 将对应的桶位指向null,方便jvm回收
oldTab[j] = null;

// 1.如果只有一个节点
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;

// 2.树化了
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);

// 3.还是链表
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;

// 比如e.hash只能为两种可能 1 1111 或者 0 1111 , oldCap 为 10000

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;
}

整体步骤:

  1. 计算新桶数组的容量 newCap 和新阈值 newThr
  2. 根据计算出的 newCap 创建新的桶数组,桶数组 table 也是在这里进行初始化的
  3. 将键值对节点重新映射到新的桶数组里。如果节点是 TreeNode 类型,则需要拆分红黑树。如果是普通节点,则节点按原顺序进行分组。

总结起来,一共有三种扩容方式

  1. 使用默认构造方法初始化HashMap。从前文可以知道HashMap在一开始初始化的时候会返回一个空的table,并且thershold为0。因此第一次扩容的容量为默认值DEFAULT_INITIAL_CAPACITY也就是16。同时threshold = DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR = 12。

  2. 指定初始容量的构造方法初始化HashMap。那么从下面源码可以看到初始容量会等于threshold,接着threshold = 当前的容量(threshold) * DEFAULT_LOAD_FACTOR。

  3. HashMap不是第一次扩容。如果HashMap已经扩容过的话,那么每次table的容量以及threshold量为原有的两倍。

细心点的人会很好奇,为什么要判断loadFactor为0呢?

loadFactor小数位为 0,整数位可被2整除且大于等于8时,在某次计算中就可能会导致 newThr 溢出归零。

2.5 get方法分析

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
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

final Node<K,V> getNode(int hash, Object key) {
// tab:引用当前hashmap的table
// first:桶位中的头元素
// n:table的长度
// e:是临时Node元素
// k:是key的临时变量
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

// 1.如果哈希表为空,或key对应的桶为空,返回null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {

// 2.这个桶的头元素就是想要找的
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;

// 说明当前桶位不止一个元素,可能是链表,也可能是红黑树
if ((e = first.next) != null) {
// 3.树化了
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);

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

2.6 remove方法分析

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 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) {
// tab:引用当前hashmap的table
// p:当前的node元素
// n:当前的散列表数组长度
// index:表示寻址结果
Node<K,V>[] tab; Node<K,V> p; int n, index;

// 1.如果数组table为空或key映射到的桶为空,返回null。
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {

// node:查找到的结果
// e:当前Node的下一个元素
Node<K,V> node = null, e; K k; V v;

// 2.桶位的头元素就是我们要找的
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;

else if ((e = p.next) != null) {
// 3.树化了
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
// 4.链表中
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不为null,说明按照key查找到想要删除的数据了
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;
}

2.7 replace方法分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Override
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}

@Override
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}

2.8 其他常用方法

isEmpty()

1
2
3
4
5
6
7
8
/**
* 如果map中没有键值对映射,返回true
*
* @return <如果map中没有键值对映射,返回true
*/
public boolean isEmpty() {
return size == 0;
}

putMapEntries()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
// table为null,代表这里使用HashMap(Map<? extends K, ? extends V> m)构造函数 或者其它方式实例化hashmap但是还没往里面添加过元素
if (table == null) { // pre-size
//前面讲到,initial capacity*load factor就是当前hashMap允许的最大元素数目。那么不难理解,s/loadFactor+1即为应该初始化的容量。
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
//table已经初始化,并且map的大小大于临界值
else if (s > threshold)
//扩容处理
resize();
//将map中所有键值对添加到hashMap中
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}

putAll()

1
2
3
4
5
6
7
8
/**
* 将参数map中的所有键值对映射插入到hashMap中,如果有碰撞,则覆盖value。
* @param m 参数map
* @throws NullPointerException 如果map为null
*/
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}

clear()

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 删除map中所有的键值对
*/
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;
}
}

containsValue( Object value)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 如果hashMap中的键值对有一对或多对的value为参数value,返回true
*
* @param value 参数value
* @return 如果hashMap中的键值对有一对或多对的value为参数value,返回true
*/
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
//
if ((tab = table) != null && size > 0) {
//遍历数组table
for (int i = 0; i < tab.length; ++i) {
//遍历桶中的node
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}

3.疑问和解答

1. JDK1.7是基于数组+单链表实现(为什么不用双链表)

首先,用链表是为了解决hash冲突。

单链表能实现为什么要用双链表呢?(双链表需要更大的存储空间)

2. 为什么要用红黑树,而不用平衡二叉树?

插入效率比平衡二叉树高,查询效率比普通二叉树高。所以选择性能相对折中的红黑树。

3. 重写对象的Equals方法时,要重写hashCode方法,为什么?跟HashMap有什么关系?

equals与hashcode间的关系:

  1. 如果两个对象相同(即用equals比较返回true),那么它们的hashCode值一定要相同;
  2. 如果两个对象的hashCode相同,它们并不一定相同(即用equals比较返回false)

因为在 HashMap 的链表结构中遍历判断的时候,特定情况下重写的 equals 方法比较对象是否相等的业务逻辑比较复杂,循环下来更是影响查找效率。所以这里把 hashcode 的判断放在前面,只要 hashcode 不相等就玩儿完,不用再去调用复杂的 equals 了。很多程度地提升 HashMap 的使用效率。

所以重写 hashcode 方法是为了让我们能够正常使用 HashMap 等集合类,因为 HashMap 判断对象是否相等既要比较 hashcode 又要使用 equals 比较。而这样的实现是为了提高 HashMap 的效率。

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;
}

4. 既然红黑树那么好,为啥hashmap不直接采用红黑树,而是当大于8个的时候才转换红黑树?

因为红黑树需要进行左旋,右旋操作, 而单链表不需要。

以下都是单链表与红黑树结构对比。

如果元素小于8个,查询成本高,新增成本低。

如果元素大于8个,查询成本低,新增成本高。

至于为什么选数字8,是大佬折中衡量的结果,就像loadFactor默认值0.75一样。

5. JDK1.8的HashMap在链表插入时是尾插法,而1.7是头插法,为什么?

HashMap在jdk1.7中采用头插入法,在扩容时会改变链表中元素原本的顺序,以至于在并发场景下导致链表成环的问题。而在jdk1.8中采用尾插入法,在扩容时会保持链表元素原本的顺序,就不会出现链表成环的问题了。

6. 总结下HashMap在1.7和1.8之间的变化:

  • 1.7采用数组+单链表,1.8在单链表超过一定长度后改成红黑树存储。

  • 1.7扩容时需要重新计算哈希值和索引位置,1.8并不重新计算哈希值,巧妙地采用和扩容后容量进行&操作来计算新的索引位置。

  • 1.7插入元素到单链表中采用头插入法,1.8采用的是尾插入法。

4.参考

HashMap全B站最细致源码分析课程

HashMap源码分析