来自微信公众号:I am CR7
HashMap
作为哈希表的Map接口实现,其具备以下几个特点:
和HashTable类似,采用数组+单链表形式存储元素,从jdk1.8开始,增加了红黑树的结构,当单链表中元素个数超过指定阈值,会转化为红黑树结构存储,目的就是为了解决单链表元素过多时查询慢的问题。
和HashTable不同的是,HashMap是线程不安全的,方法都未使用synchronized关键字。因为内部实现不同,允许key和value值为null。
构建HashMap实例时有两个重要的参数,会影响其性能:初始大小和加载因子。初始大小用来规定哈希表数组的长度,即桶的个数。加载因子用来表示哈希表元素的填满程度,越大则表示允许填满的元素就越多,哈希表的空间利用率就越高,但是冲突的机会也就增加了。反之,越小则冲突的机会就会越少,但是空间很多就浪费了。
静态常量
1、源码:
1
4static final int DEFAULT_INITIAL_CAPACITY = 1 <4;
5
6
9static final int MAXIMUM_CAPACITY = 1 <30;
10
11
14static final float DEFAULT_LOAD_FACTOR = 0.75f;
15
16
19static final int TREEIFY_THRESHOLD = 8;
20
21
25static final int UNTREEIFY_THRESHOLD = 6;
26
27
31static final int MIN_TREEIFY_CAPACITY = 64;
注意:HashMap默认采用数组+单链表方式存储元素,当元素出现哈希冲突时,会存储到该位置的单链表中。但是单链表不会一直增加元素,当元素个数超过8个时,会尝试将单链表转化为红黑树存储。但是在转化前,会再判断一次当前数组的长度,只有数组长度大于64才处理。否则,进行扩容操作。此处先提到这,后续会有详细的讲解。
2、问题:
问:为何加载因子默认为0.75?
答:通过源码里的javadoc注释看到,元素在哈希表中分布的桶频率服从参数为0.5的泊松分布,具体可以参考下StackOverflow里的解答:https://stackoverflow.com/questions/10901752/what-is-the-significance-of-load-factor-in-hashmap
构造函数
1、无参构造函数:
1public HashMap() {
2 this.loadFactor = DEFAULT_LOAD_FACTOR;
3}
2、带参构造函数,指定初始容量:
1public HashMap(int initialCapacity) {
2 this(initialCapacity, DEFAULT_LOAD_FACTOR);
3}
3、带参构造函数,指定初始容量和加载因子:
3.1、源码:
1public HashMap(int initialCapacity, float loadFactor) {
2 if (initialCapacity 0)
3 throw new IllegalArgumentException("Illegal initial capacity: " +
4 initialCapacity);
5 if (initialCapacity > MAXIMUM_CAPACITY)
6 initialCapacity = MAXIMUM_CAPACITY;
7 if (loadFactor <= 0 || Float.isNaN(loadFactor))
8 throw new IllegalArgumentException("Illegal load factor: " +
9 loadFactor);
10 this.loadFactor = loadFactor;
11 this.threshold = tableSizeFor(initialCapacity)
12}
13
14
15static final int tableSizeFor(int cap) {
16 int n = cap - 1;
17 n |= n >>> 1;
18 n |= n >>> 2;
19 n |= n >>> 4;
20 n |= n >>> 8;
21 n |= n >>> 16;
22 return (n 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
23}
3.2、示例:
下面我们以cap等于8为例:
不减一的过程如下:
最后执行加1操作,那么返回的是2^4=16,是cap的2倍。
减一的过程如下:
最后执行加1操作,那么返回的是2^3=8,也就是cap本身。
3.3、问题:
问:为何数组容量必须是2次幂?
答:索引计算公式为i = (n - 1) & hash,如果n为2次幂,那么n-1的低位就全是1,哈希值进行与操作时可以保证低位的值不变,从而保证分布均匀,效果等同于hash%n,但是位运算比取余运算要高效的多。
4、带参构造函数,指定Map集合:
1public HashMap(Map extends K, ? extends V> m) {
2 this.loadFactor = DEFAULT_LOAD_FACTOR;
3 putMapEntries(m, false);
4}
5
6final void putMapEntries(Map extends K, ? extends V> m, boolean evict) {
7 int s = m.size();
8 if (s > 0) {
9 if (table == null) {
10 float ft = ((float)s / loadFactor) + 1.0F;
11 int t = ((ft 12 (int)ft : MAXIMUM_CAPACITY);
13 if (t > threshold)
14 threshold = tableSizeFor(t);
15 }
16 else if (s > threshold)
17 resize();
18 for (Map.Entry extends K, ? extends V> e : m.entrySet()) {
19 K key = e.getKey();
20 V value = e.getValue();
21 putVal(hash(key), key, value, false, evict);
22 }
23 }
24}
添加元素
1、源码:
1public V put(K key, V value) {
2 return putVal(hash(key), key, value, false, true);
3}
4
5
6static final int hash(Object key) {
7 int h;
8 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
9}
10
11final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
12 boolean evict) {
13 Node[] tab; Node p; int n, i;
14
15 if ((tab = table) == null || (n = tab.length) == 0)
16 n = (tab = resize()).length;
17
18
19 if ((p = tab[i = (n - 1) & hash]) == null)
20 tab[i] = newNode(hash, key, value, null);
21 else {
22 Node e; K k;
23
24 if (p.hash == hash &&
25 ((k = p.key) == key || (key != null && key.equals(k))))
26 e = p;
27 else if (p instanceof TreeNode)
28 e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
29 else {
30 for (int binCount = 0; ; ++binCount) {
31 if ((e = p.next) == null) {
32 p.next = newNode(hash, key, value, null);
33 if (binCount >= TREEIFY_THRESHOLD - 1)
34 treeifyBin(tab, hash);
35 break;
36 }
37 if (e.hash == hash &&
38 ((k = e.key) == key || (key != null && key.equals(k))))
39 break;
40 p = e;
41 }
42 }
43 if (e != null) {
44 V oldValue = e.value;
45 if (!onlyIfAbsent || oldValue == null)
46 e.value = value;
47 afterNodeAccess(e);
48 return oldValue;
49 }
50 }
51 ++modCount;
52 if (++size > threshold)
53 resize();
54 afterNodeInsertion(evict);
55 return null;
56}
2、流程图:
3、hash计算:
问:获取hash值时:为何在hash方法中加上异或无符号右移16位的操作?
答:此方式是采用"扰乱函数"的解决方案,将key的哈希值,进行高16位和低16位异或操作,增加低16位的随机性,降低哈希冲突的可能性。
下面我们通过一个例子,来看下有无"扰乱函数"的情况下,计算出来索引位置的值:
由上图可知,增加"扰乱函数"之后,原本哈希冲突的情况并没有再出现。扩容
1、源码:
1final Node[] resize() {
2 Node[] oldTab = table;
3 int oldCap = (oldTab == null) ? 0 : oldTab.length;
4 int oldThr = threshold;
5 int newCap, newThr = 0;
6 if (oldCap > 0) {
7 if (oldCap >= MAXIMUM_CAPACITY) {
8 threshold = Integer.MAX_VALUE;
9 return oldTab;
10 }
11 else if ((newCap = oldCap <1) 12 oldCap >= DEFAULT_INITIAL_CAPACITY)
13 newThr = oldThr <1;
14 }
15 else if (oldThr > 0)
16 newCap = oldThr;
17 else {
18 newCap = DEFAULT_INITIAL_CAPACITY;
19 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
20 }
21 if (newThr == 0) {
22 float ft = (float)newCap * loadFactor;
23 newThr = (newCap float)MAXIMUM_CAPACITY ?
24 (int)ft : Integer.MAX_VALUE);
25 }
26 threshold = newThr;
27 @SuppressWarnings({"rawtypes","unchecked"})
28 Node[] newTab = (Node[])new Node[newCap];
29 table = newTab;
30 if (oldTab != null) {
31 for (int j = 0; j 32 Node e;
33 if ((e = oldTab[j]) != null) {
34 oldTab[j] = null;
35 if (e.next == null)
36 newTab[e.hash & (newCap - 1)] = e;
37 else if (e instanceof TreeNode)
38 ((TreeNode)e).split(this, newTab, j, oldCap);
39 else {
40 Node loHead = null, loTail = null;
41 Node hiHead = null, hiTail = null;
42 Node next;
43 do {
44 next = e.next;
45 if ((e.hash & oldCap) == 0) {
46 if (loTail == null)
47 loHead = e;
48 else
49 loTail.next = e;
50 loTail = e;
51 }
52 else {
53 if (hiTail == null)
54 hiHead = e;
55 else
56 hiTail.next = e;
57 hiTail = e;
58 }
59 } while ((e = next) != null);
60 if (loTail != null) {
61 loTail.next = null;
62 newTab[j] = loHead;
63 }
64 if (hiTail != null) {
65 hiTail.next = null;
66 newTab[j + oldCap] = hiHead;
67 }
68 }
69 }
70 }
71 }
72 return newTab;
73}
2、流程图:
2.1 首次调用扩容方法:
2.2 示例:
情况一:
使用无参构造函数:
1HashMap hashMap = new HashMap<>();
put元素,发现table为null,调用resize扩容方法:
1int oldCap = (oldTab == null) ? 0 : oldTab.length;
2int oldThr = threshold;
oldCap为0,oldThr为0,执行resize()里的该分支:
1newCap = DEFAULT_INITIAL_CAPACITY;
2newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
3threshold = newThr;
4@SuppressWarnings({"rawtypes","unchecked"})
5 Node[] newTab = (Node[])new Node[newCap];
6table = newTab;
newCap为16,newThr为12,也就是说HashMap默认数组长度为16,元素添加阈值为12。
threshold为12。创建大小为16的数组,赋值给table。
情况二:
使用有参构造函数:
1HashMap hashMap = new HashMap<>(7);
oldCap为0,oldThr为8,执行resize()里的该分支:
1else if (oldThr > 0)
2 newCap = oldThr;
newCap为8,newThr为0,执行resize()里的该分支:
1if (newThr == 0) {
2 float ft = (float)newCap * loadFactor;
3 newThr = (newCap float)MAXIMUM_CAPACITY ?
4 (int)ft : Integer.MAX_VALUE);
5}
6threshold = newThr;
7@SuppressWarnings({"rawtypes","unchecked"})
8 Node[] newTab = (Node[])new Node[newCap];
9table = newTab;
threshold为6。创建大小为8的数组,赋值给table。
2.3 非首次调用扩容方法:
2.4 示例:
接着2.2里的情况二,继续添加元素,直到扩容:
oldCap为8,oldThr为6,执行resize()里的该分支:
1if (oldCap > 0) {
2 if (oldCap >= MAXIMUM_CAPACITY) {
3 threshold = Integer.MAX_VALUE;
4 return oldTab;
5 }
6 else if ((newCap = oldCap <1) 7 oldCap >= DEFAULT_INITIAL_CAPACITY)
8 newThr = oldThr <1;
9}
oldCap小于MAXIMUM_CAPACITY,进行2倍扩容,newCap为16。oldCap小于DEFAULT_INITIAL_CAPACITY,不做newThr的扩容,为0,执行resize()里的该分支:
1if (newThr == 0) {
2 float ft = (float)newCap * loadFactor;
3 newThr = (newCap float)MAXIMUM_CAPACITY ?
4 (int)ft : Integer.MAX_VALUE);
5}
6threshold = newThr;
7@SuppressWarnings({"rawtypes","unchecked"})
8 Node[] newTab = (Node[])new Node[newCap];
9table = newTab;
10..........省略.......
因为newCap小于MAXIMUM_CAPACITY ,ft为newCap*加载因子为12,threshold为12。创建大小为16的数组,赋值给table,并将原数组元素放入新数组中。
继续添加元素,直到扩容:
oldCap为16,oldThr为12,执行resize()里的该分支:
1if (oldCap > 0) {
2 if (oldCap >= MAXIMUM_CAPACITY) {
3 threshold = Integer.MAX_VALUE;
4 return oldTab;
5 }
6 else if ((newCap = oldCap <1) 7 oldCap >= DEFAULT_INITIAL_CAPACITY)
8 newThr = oldThr <1;
9}
oldCap小于MAXIMUM_CAPACITY,将数组长度进行2倍扩容,newCap为32。oldCap>=DEFAULT_INITIAL_CAPACITY,将添加元素的阈值也进行2倍扩容,注意此时不再用加载因子去计算阈值,而是随着数组长度进行相应的2倍扩容,threshold为24。
创建大小为32的数组,赋值给table,并将原数组元素放入新数组中。
1threshold = newThr;
2@SuppressWarnings({"rawtypes","unchecked"})
3 Node[] newTab = (Node[])new Node[newCap];
4table = newTab;
5..........省略.......
继续添加元素,扩容到数组长度等于MAXIMUM_CAPACITY:
oldCap为MAXIMUM_CAPACITY,执行resize()里的该分支:
1if (oldCap > 0) {
2 if (oldCap >= MAXIMUM_CAPACITY) {
3 threshold = Integer.MAX_VALUE;
4 return oldTab;
5 }
6 else if ((newCap = oldCap <1) 7 oldCap >= DEFAULT_INITIAL_CAPACITY)
8 newThr = oldThr <1;
9}
因为oldCap等于MAXIMUM_CAPACITY,threshold设置为 Integer.MAX_VALUE,不再扩容,直接返回原数组。此时继续添加元素,Integer.MAX_VALUE+1=Integer.MIN_VALUE,不再大于threshold,则不再进行扩容操作了。
树化操作
1、源码:
将原本的单链表转化为双向链表,再遍历这个双向链表转化为红黑树:
1final void treeifyBin(Node[] tab, int hash) {
2 int n, index; Node e;
3
4 if (tab == null || (n = tab.length) 5 resize();
6 else if ((e = tab[index = (n - 1) & hash]) != null) {
7 TreeNode hd = null, tl = null;
8 do {
9 TreeNode p = replacementTreeNode(e, null);
10 if (tl == null)
11 hd = p;
12 else {
13 p.prev = tl;
14 tl.next = p;
15 }
16 tl = p;
17 } while ((e = e.next) != null);
18
19 if ((tab[index] = hd) != null)
20 hd.treeify(tab);
21 }
22}
将双向链表转化为红黑树的具体实现:
1final void treeify(Node[] tab) {
2 TreeNode root = null;
3 for (TreeNode x = this, next; x != null; x = next) {
4 next = (TreeNode)x.next;
5 x.left = x.right = null;
6 if (root == null) {
7 x.parent = null;
8 x.red = false;
9 root = x;
10 }
11 else {
12 K k = x.key;
13 int h = x.hash;
14 Class> kc = null;
15 for (TreeNode p = root;;) {
16 int dir, ph;
17 K pk = p.key;
18 if ((ph = p.hash) > h)
19 dir = -1;
20 else if (ph // 当前红黑树节点的hash值小于双向链表节点x的哈希值
21 dir = 1;
22 else if ((kc == null &&
23 (kc = comparableClassFor(k)) == null) ||
24 (dir = compareComparables(kc, k, pk)) == 0)
25 dir = tieBreakOrder(k, pk);
26
27 TreeNode xp = p;
28 if ((p = (dir <= 0) ? p.left : p.right) == null) {
29 x.parent = xp;
30 if (dir <= 0)
31 xp.left = x;
32 else
33 xp.right = x;
34 root = balanceInsertion(root, x);
35 break;
36 }
37 }
38 }
39 }
40
41 moveRootToFront(tab, root);
42}
将红黑树的根节点移动到数组的索引所在位置上:
1static void moveRootToFront(Node[] tab, TreeNode root) {
2 int n;
3 if (root != null && tab != null && (n = tab.length) > 0) {
4 int index = (n - 1) & root.hash;
5 TreeNode first = (TreeNode)tab[index];
6 if (root != first) {
7 Node rn;
8 tab[index] = root;
9 TreeNode rp = root.prev;
10 if ((rn = root.next) != null)
11 ((TreeNode)rn).prev = rp;
12 if (rp != null)
13 rp.next = rn;
14 if (first != null)
15 first.prev = root;
16 root.next = first;
17 root.prev = null;
18 }
19 assert checkInvariants(root);
20 }
21}
红黑树插入
1、源码:
1final TreeNode putTreeVal(HashMap map, Node[] tab,
2 int h, K k, V v) {
3 Class> kc = null;
4 boolean searched = false;
5 TreeNode root = (parent != null) ? root() : this;
6 for (TreeNode p = root;;) {
7 int dir, ph; K pk;
8 if ((ph = p.hash) > h)
9 dir = -1;
10 else if (ph 11 dir = 1;
12 else if ((pk = p.key) == k || (k != null && k.equals(pk)))
13 return p;
14 else if ((kc == null &&
15 (kc = comparableClassFor(k)) == null) ||
16 (dir = compareComparables(kc, k, pk)) == 0) {
17 if (!searched) {
18 TreeNode q, ch;
19 searched = true;
20 if (((ch = p.left) != null &&
21 (q = ch.find(h, k, kc)) != null) ||
22 ((ch = p.right) != null &&
23 (q = ch.find(h, k, kc)) != null))
24 return q;
25 }
26 dir = tieBreakOrder(k, pk);
27 }
28
29 TreeNode xp = p;
30 if ((p = (dir <= 0) ? p.left : p.right) == null) {
31 Node xpn = xp.next;
32 TreeNode x = map.newTreeNode(h, k, v, xpn);
33 if (dir <= 0)
34 xp.left = x;
35 else
36 xp.right = x;
37 xp.next = x;
38 x.parent = x.prev = xp;
39 if (xpn != null)
40 ((TreeNode)xpn).prev = x;
41 moveRootToFront(tab, balanceInsertion(root, x));
42 return null;
43 }
44 }
45}
2、说明:
当hash冲突时,单链表元素个数超过树化阈值(TREEIFY_THRESHOLD)后,转化为红黑树存储。之后再继续冲突,则就变成往红黑树中插入元素了。关于红黑树插入元素,请看我之前写的文章:TreeMap之元素插入
红黑树拆分
1、源码:
将红黑树按照扩容后的数组,重新计算索引位置,并且拆分后的红黑树还需要判断个数,从而决定是做去树化操作还是树化操作:
1final void split(HashMap map, Node[] tab, int index, int bit) {
2 TreeNode b = this;
3
4 TreeNode loHead = null, loTail = null;
5 TreeNode hiHead = null, hiTail = null;
6 int lc = 0, hc = 0;
7 for (TreeNode e = b, next; e != null; e = next) {
8 next = (TreeNode)e.next;
9 e.next = null;
10 if ((e.hash & bit) == 0) {
11 if ((e.prev = loTail) == null)
12 loHead = e;
13 else
14 loTail.next = e;
15 loTail = e;
16 ++lc;
17 }
18 else {
19 if ((e.prev = hiTail) == null)
20 hiHead = e;
21 else
22 hiTail.next = e;
23 hiTail = e;
24 ++hc;
25 }
26 }
27
28 if (loHead != null) {
29 if (lc <= UNTREEIFY_THRESHOLD)
30 tab[index] = loHead.untreeify(map);
31 else {
32 tab[index] = loHead;
33 if (hiHead != null)
34 loHead.treeify(tab);
35 }
36 }
37 if (hiHead != null) {
38 if (hc <= UNTREEIFY_THRESHOLD)
39 tab[index + bit] = hiHead.untreeify(map);
40 else {
41 tab[index + bit] = hiHead;
42 if (loHead != null)
43 hiHead.treeify(tab);
44 }
45 }
46}
去树化操作
1、源码:
遍历红黑树,还原成单链表结构:
1final Node untreeify(HashMap map) {
2 Node hd = null, tl = null;
3 for (Node q = this; q != null; q = q.next) {
4 Node p = map.replacementNode(q, null);
5 if (tl == null)
6 hd = p;
7 else
8 tl.next = p;
9 tl = p;
10 }
11 return hd;
12}
综合示例
1、代码:
1
2HashMap hashMap = new HashMap<>(64);
3for(int i=0; i<38; i++){
4 hashMap.put(i, i);
5}
6
7for (int i=1; i <= 7; i++) {
8 hashMap.put(64*i, 64*i);
9}
10
11hashMap.put(64*8, 64*8);
12
13hashMap.put(64*9, 64*9);
14
15hashMap.put(38, 38);
16
17hashMap.put(39, 39);
2、内部实现过程:
讨论题
为何单链表转化为红黑树,要求节点个数大于8?
为何转化为红黑树前,要求数组总长度要大于64?
为何红黑树转化为单链表,要求节点个数小于等于6?
●编号751,输入编号直达本文
●输入m获取文章目录
大数据与人工智能
更多推荐《18个技术类公众微信》
涵盖:程序人生、算法与数据结构、黑客技术与网络安全、大数据技术、前端开发、Java、Python、Web开发、安卓开发、iOS开发、C/C++、.NET、Linux、数据库、运维等。