HashMap的内部存储是以数组+链表+红黑树为组合的复合结构,数组(table)中元素是Entry,键值对(key-value)中key的hashCode值决定了Entry元素在数组中的位置,当发生hash冲突时,相同hash值的Entry元素组成链表,链表的长度是有定长的(TREEIFY_THRESHOLD=8),当链表触发链表树化,就会变成树形结构。

1
2
3
4
5
6
7
/**
* 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.)
*/
transient Node<K,V>[] table;
  • 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
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*
* 计算key.hashCode()并且移动高位到低位。由于数组使用2的幂次表示,变化仅仅在hash集合
* 的上方中这将总是发生碰撞(这其中的例子是Float的key集合在小的table中保持连续的数
* 字),所以我们应用高位向下移动的影响来作为转化。在速度、实用和为扩展上需要权衡,由于
* 许多哈希集已经合理的分布(所以无需从移动位中受益),并且因为我们使用了树来处理容器中
* 更大的冲突,因此我们仅以最简答单的方式对一些以为后的微bit进行XOR,以减少系统损耗,
* 以及最高位的影响,否则由于table番位的限制,这些高位将永远不会在索引计算中使用。
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

可以看到hash方法中将Object key计算出的hashCode右移了16位,这里的原因官方注释中已经很明了,这样做是为了将高位的信息在hash值进行计算索引中降低冲突的概率,因为在一些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
/**
* 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;
this.threshold = tableSizeFor(initialCapacity);
}

/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}

看到HashMap1.8中四个构造函数,主要就看第一个,两个入参initialCapacity是table数组的大小,默认值DEFAULT_INITIAL_CAPACITY=16,loadFactor负载因子用来控制扩容的阈值默认DEFAULT_LOAD_FACTOR=0.75f,就是当table的threshold到达0.75时触发table扩容。这里tableSizeFor(initialCapacity)方法是利用传入的初始化table容量转为2的幂次数。

  • 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
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
/**
* 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>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

/**
* 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;
if ((tab = table) == null || (n = tab.length) == 0)//(1)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)//(2)
tab[i] = newNode(hash, key, value, null);
else {//(3)
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//(4)
e = p;
else if (p instanceof TreeNode)//(5)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//(6)
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))))//(7)
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;//(8)
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//(9)
if (++size > threshold)//(10)
resize();
afterNodeInsertion(evict);
return null;
}

这里主要看putVal()方法。
(1)这里第一个if判断table是否为空,为空就利用resize方法初始化;
(2)第二个if判断如果当前根据hash跟到的table索引下为空就直接将Node对象放入table中;
(3)else下是hash发生碰撞;
(4)首先第一个if判断的是如果NewNode和table中位置的Node hash值和key都相同就直接可以看作是同一个Node,这里还有个场景是否用新put的values覆盖老的value,onlyIfAbsent为false或者老的value为空就要覆盖掉老值;
(5)else if判断如果是一个树结点就调用putTreeVal插入元素;
(6)else下循环遍历将p添加到链表尾部,如果这时达到链表最大阈值就需要调用treeifyBin方法进行树化;
(7)如果已经在链表中就braek掉;
(8)这里判断是否需要覆盖老数据。
(9)modCount保证并发访问,这里的put方法是线程不安全的,所以当modCount发现变化不一致就会抛出ConcurrentModificationException。

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
117
118
119
120
  final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
```

(10)这里对table扩容。

* resize方法

``` java
/**
* 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
*
* 初始化或增加成两倍大的table,如果为空,则根据字段阈值中保持的初始容量目标进行分配。
* 否则,因为我们使用的是2的幂,所以每个bin中的元素必须保持相同的索引,或者在新表中以2
* 的幂偏移。
*/
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) {
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) {//(1)
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
//(2)
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;
}

上面的代码基本都很好理解的,这里主要说两个点:
(1)这个位置是table变成两倍table的元素移动的操作,e.nex=null说明它就是一个元素不存在链和树直接根据e.hash & (newCap - 1)计算出它在新table中的位置并赋值;如果是树通过split方法复制树;
(2)这里比较重要的操作。这里是链表复制的过程,这里链表上的Node位置有两个场景,一种是不需要移动的Node形成链表还在老的index下,另一种是需要我们移动位置的Node形成新的链表复制到新的index下。这里为什么会有这个操作,因为index值的确定是根据Node.hash和cap-1取与获得的,那么在变成两倍table后讲道理每一个index都需要重新取计算,但是这里观察变成两倍table的原理其实每次threshold<<1(也就是二进制高位变成1),那么这样Node.hash和cap-1取与过程中发生变化的就只有高位是1的所以这里(e.hash & oldCap) == 0表示在变成两倍table后index不需要变化,如果需要变化那么index=老idnex+oldCap。

  • 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
39
40
41
42
43
44
45
46
47
48
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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;
}

get方法相对简单直接通过key和hash取查找元素,如果是table中的first直接返回如果是tree从tree遍历g得到,如果是链表遍历拿到。

  • 总结
    hash()方法的关键是高位右移的操作,目的是为了使得hash趋于均匀分布,避免hash冲突(碰撞),在与table.length取与获得index时尽降低形成链
    put()方法完成table创建和初始化和新增Node,新增Node分三个场景直接放置在table[index]位置;形成链表的插入链表中,链表达到阈值形成红黑树
    resize()方法完成 两倍扩展以及扩展后的Node的重新放置,这里重要是巧妙的使用 (e.hash & oldCap) == 0来作为是否将老链表数据分开放置的处理,利用扩容和2的幂的关系进行操作