forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashMap.java
3324 lines (2834 loc) · 132 KB
/
HashMap.java
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import jdk.internal.misc.SharedSecrets;
/**
* Hash table based implementation of the {@code Map} interface. This
* implementation provides all of the optional map operations, and permits
* {@code null} values and the {@code null} key. (The {@code HashMap}
* class is roughly equivalent to {@code Hashtable}, except that it is
* unsynchronized and permits nulls.) This class makes no guarantees as to
* the order of the map; in particular, it does not guarantee that the order
* will remain constant over time.
*
* <p>This implementation provides constant-time performance for the basic
* operations ({@code get} and {@code put}), assuming the hash function
* disperses the elements properly among the buckets. Iteration over
* collection views requires time proportional to the "capacity" of the
* {@code HashMap} instance (the number of buckets) plus its size (the number
* of key-value mappings). Thus, it's very important not to set the initial
* capacity too high (or the load factor too low) if iteration performance is
* important.
*
* <p>An instance of {@code HashMap} has two parameters that affect its
* performance: <i>initial capacity</i> and <i>load factor</i>. The
* <i>capacity</i> is the number of buckets in the hash table, and the initial
* capacity is simply the capacity at the time the hash table is created. The
* <i>load factor</i> is a measure of how full the hash table is allowed to
* get before its capacity is automatically increased. When the number of
* entries in the hash table exceeds the product of the load factor and the
* current capacity, the hash table is <i>rehashed</i> (that is, internal data
* structures are rebuilt) so that the hash table has approximately twice the
* number of buckets.
*
* <p>As a general rule, the default load factor (.75) offers a good
* tradeoff between time and space costs. Higher values decrease the
* space overhead but increase the lookup cost (reflected in most of
* the operations of the {@code HashMap} class, including
* {@code get} and {@code put}). The expected number of entries in
* the map and its load factor should be taken into account when
* setting its initial capacity, so as to minimize the number of
* rehash operations. If the initial capacity is greater than the
* maximum number of entries divided by the load factor, no rehash
* operations will ever occur.
*
* <p>If many mappings are to be stored in a {@code HashMap}
* instance, creating it with a sufficiently large capacity will allow
* the mappings to be stored more efficiently than letting it perform
* automatic rehashing as needed to grow the table. Note that using
* many keys with the same {@code hashCode()} is a sure way to slow
* down performance of any hash table. To ameliorate impact, when keys
* are {@link Comparable}, this class may use comparison order among
* keys to help break ties.
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access a hash map concurrently, and at least one of
* the threads modifies the map structurally, it <i>must</i> be
* synchronized externally. (A structural modification is any operation
* that adds or deletes one or more mappings; merely changing the value
* associated with a key that an instance already contains is not a
* structural modification.) This is typically accomplished by
* synchronizing on some object that naturally encapsulates the map.
*
* If no such object exists, the map should be "wrapped" using the
* {@link Collections#synchronizedMap Collections.synchronizedMap}
* method. This is best done at creation time, to prevent accidental
* unsynchronized access to the map:<pre>
* Map m = Collections.synchronizedMap(new HashMap(...));</pre>
*
* <p>The iterators returned by all of this class's "collection view methods"
* are <i>fail-fast</i>: if the map is structurally modified at any time after
* the iterator is created, in any way except through the iterator's own
* {@code remove} method, the iterator will throw a
* {@link ConcurrentModificationException}. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw {@code ConcurrentModificationException} on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* <p>This class is a member of the
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
* Java Collections Framework</a>.
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*
* @author Doug Lea
* @author Josh Bloch
* @author Arthur van Hoff
* @author Neal Gafter
* @see Object#hashCode()
* @see Collection
* @see Map
* @see TreeMap
* @see Hashtable
* @since 1.2
*/
/*
* HashMap结构:哈希数组+链表/红黑树,key和value均可以为null
*
* 存储元素时,需要调用key的hashCode()方法,计算出一个哈希值
* 1.哈希值相同的元素,必定位于同一个哈希槽(链)上,但不能确定这两个元素是不是同位元素
* 在进一步判断key如果相等(必要时需要调用equals()方法)时,才能确定这两个元素属于同位元素
* 如果是存储同位元素,需要考虑是否允许覆盖旧值的问题
* 2.哈希值不同的元素,它们也可能位于同一个哈希槽(链)上,但它们肯定不是同位元素
*
* 注:HashMap非线程安全。如果需要考虑并发,则需要使用ConcurrentHashMap
*/
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
/*
* Implementation notes.
*
* This map usually acts as a binned (bucketed) hash table, but
* when bins get too large, they are transformed into bins of
* TreeNodes, each structured similarly to those in
* java.util.TreeMap. Most methods try to use normal bins, but
* relay to TreeNode methods when applicable (simply by checking
* instanceof a node). Bins of TreeNodes may be traversed and
* used like any others, but additionally support faster lookup
* when overpopulated. However, since the vast majority of bins in
* normal use are not overpopulated, checking for existence of
* tree bins may be delayed in the course of table methods.
*
* Tree bins (i.e., bins whose elements are all TreeNodes) are
* ordered primarily by hashCode, but in the case of ties, if two
* elements are of the same "class C implements Comparable<C>",
* type then their compareTo method is used for ordering. (We
* conservatively check generic types via reflection to validate
* this -- see method comparableClassFor). The added complexity
* of tree bins is worthwhile in providing worst-case O(log n)
* operations when keys either have distinct hashes or are
* orderable, Thus, performance degrades gracefully under
* accidental or malicious usages in which hashCode() methods
* return values that are poorly distributed, as well as those in
* which many keys share a hashCode, so long as they are also
* Comparable. (If neither of these apply, we may waste about a
* factor of two in time and space compared to taking no
* precautions. But the only known cases stem from poor user
* programming practices that are already so slow that this makes
* little difference.)
*
* Because TreeNodes are about twice the size of regular nodes, we
* use them only when bins contain enough nodes to warrant use
* (see TREEIFY_THRESHOLD). And when they become too small (due to
* removal or resizing) they are converted back to plain bins. In
* usages with well-distributed user hashCodes, tree bins are
* rarely used. Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* more: less than 1 in ten million
*
* The root of a tree bin is normally its first node. However,
* sometimes (currently only upon Iterator.remove), the root might
* be elsewhere, but can be recovered following parent links
* (method TreeNode.root()).
*
* All applicable internal methods accept a hash code as an
* argument (as normally supplied from a public method), allowing
* them to call each other without recomputing user hashCodes.
* Most internal methods also accept a "tab" argument, that is
* normally the current table, but may be a new or old one when
* resizing or converting.
*
* When bin lists are treeified, split, or untreeified, we keep
* them in the same relative access/traversal order (i.e., field
* Node.next) to better preserve locality, and to slightly
* simplify handling of splits and traversals that invoke
* iterator.remove. When using comparators on insertion, to keep a
* total ordering (or as close as is required here) across
* rebalancings, we compare classes and identityHashCodes as
* tie-breakers.
*
* The use and transitions among plain vs tree modes is
* complicated by the existence of subclass LinkedHashMap. See
* below for hook methods defined to be invoked upon insertion,
* removal and access that allow LinkedHashMap internals to
* otherwise remain independent of these mechanics. (This also
* requires that a map instance be passed to some utility methods
* that may create new nodes.)
*
* The concurrent-programming-like SSA-based coding style helps
* avoid aliasing errors amid all of the twisty pointer operations.
*/
/**
* 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.
*/
static final int MAXIMUM_CAPACITY = 1 << 30; // 哈希数组最大容量
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16; // 哈希数组默认容量
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f; // HashMap默认装载因子(负荷系数)
/**
* 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.
*/
static final int TREEIFY_THRESHOLD = 8; // 某个哈希槽(链)上的元素数量增加到此值后,这些元素进入波动期,即将从链表转换为红黑树
/**
* 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.
*/
static final int MIN_TREEIFY_CAPACITY = 64; // 哈希数组的容量至少增加到此值,且满足TREEIFY_THRESHOLD的要求时,将链表转换为红黑树
/**
* 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.
*/
static final int UNTREEIFY_THRESHOLD = 6; // 哈希槽(链)上的红黑树上的元素数量减少到此值时,将红黑树转换为链表
/**
* 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; // 哈希数组(注:哈希数组的容量跟HashMap可以存储的元素数量不是一回事)
/**
* The number of key-value mappings contained in this map.
*/
transient int size; // HashMap中的元素数量
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor; // HashMap当前使用的装载因子
/**
* The next size value at which to resize (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; // HashMap扩容阈值,【一般】由(哈希数组容量*HashMap装载因子)计算而来,HashMap中元素数量超过该阈值时,哈希数组需要扩容
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet; // entry集合
/**
* 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).
*/
transient int modCount; // 记录HashMap结构的修改次数
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Constructs an empty {@code HashMap} with the default initial capacity (16) and the default load factor (0.75).
*/
// 初始化一个哈希数组容量为16,装载因子为0.75的HashMap
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* Constructs an empty {@code HashMap} 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.
*/
// 初始化一个哈希数组容量为initialCapacity,装载因子为0.75的HashMap
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty {@code HashMap} 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
*/
// 初始化一个哈希数组容量为initialCapacity,装载因子为loadFactor的HashMap
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;
// 用初始容量信息来初始化HashMap扩容阈值,该阈值后续将作为初始化哈希数组的容量依据
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Constructs a new {@code HashMap} with the same mappings as the
* specified {@code Map}. The {@code HashMap} is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified {@code Map}.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
// 使用指定的HashMap中的元素来初始化一个新的HashMap
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
// 将指定HashMap中的元素存入到当前HashMap(允许覆盖)
putMapEntries(m, false);
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 存值 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* 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 {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with {@code key}.)
*/
// 将指定的元素(key-value)存入HashMap,并返回旧值,允许覆盖
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
// 将指定的元素(key-value)存入HashMap,并返回旧值,不允许覆盖
@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
/**
* Copies all of the mappings from the specified map to this map.
* These mappings will replace any mappings that this map had for
* any of the keys currently in the specified map.
*
* @param m mappings to be stored in this map
*
* @throws NullPointerException if the specified map is null
*/
// 将指定Map中的元素存入到当前Map(允许覆盖)
public void putAll(Map<? extends K, ? extends V> map) {
putMapEntries(map, true);
}
/*▲ 存值 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 取值 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* 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)
*/
// 根据指定的key获取对应的value,如果不存在,则返回null
public V get(Object key) {
// 根据给定的key和hash(由key计算而来)查找对应的(同位)元素,如果找不到,则返回null
Node<K,V> e = getNode(hash(key), key);
return e == null ? null : e.value;
}
// 根据指定的key获取对应的value,如果不存在,则返回指定的默认值defaultValue
@Override
public V getOrDefault(Object key, V defaultValue) {
// 根据给定的key和hash(由key计算而来)查找对应的(同位)元素,如果找不到,则返回null
Node<K,V> e = getNode(hash(key), key);
return e == null ? defaultValue : e.value;
}
/*▲ 取值 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 移除 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
*
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with {@code key}.)
*/
// 移除拥有指定key的元素,并返回刚刚移除的元素的值
public V remove(Object key) {
Node<K, V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
}
// 移除拥有指定key和value的元素,返回值表示是否移除成功
@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
/**
* Removes all of the mappings from this map.
* The map will be empty after this call returns.
*/
// 清空HashMap中所有元素
public void clear() {
Node<K, V>[] tab;
modCount++;
if((tab = table) != null && size>0) {
size = 0;
Arrays.fill(tab, null);
}
}
/*▲ 移除 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 替换 ████████████████████████████████████████████████████████████████████████████████┓ */
// 将拥有指定key的元素的值替换为newValue,并返回刚刚替换的元素的值(替换失败返回null)
@Override
public V replace(K key, V newValue) {
// 根据给定的key和hash(由key计算而来)查找对应的(同位)元素,如果找不到,则返回null
Node<K,V> e = getNode(hash(key), key);
if (e != null) {
V oldValue = e.value;
e.value = newValue;
afterNodeAccess(e);
return oldValue;
}
return null;
}
// 将拥有指定key和oldValue的元素的值替换为newValue,返回值表示是否成功替换
@Override
public boolean replace(K key, V oldValue, V newValue) {
// 根据给定的key和hash(由key计算而来)查找对应的(同位)元素,如果找不到,则返回null
Node<K,V> e = getNode(hash(key), key);
V v;
if (e != null && ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}
// 替换当前HashMap中的所有元素,替换策略由function决定,function的入参是元素的key和value,出参作为新值
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Node<K,V>[] tab;
if (function == null) {
throw new NullPointerException();
}
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (Node<K,V> e : tab) {
for (; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
if (modCount != mc) {
throw new ConcurrentModificationException();
}
}
}
/*▲ 替换 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 包含查询 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns {@code true} if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
*
* @return {@code true} if this map contains a mapping for the specified
* key.
*/
// 判断HashMap中是否存在指定key的元素
public boolean containsKey(Object key) {
// 根据给定的key和hash(由key计算而来)查找对应的(同位)元素,如果找不到,则返回null
Node<K,V> e = getNode(hash(key), key);
return e != null;
}
/**
* Returns {@code true} if this map maps one or more keys to the
* specified value.
*
* @param value value whose presence in this map is to be tested
*
* @return {@code true} if this map maps one or more keys to the
* specified value
*/
// 判断HashMap中是否存在指定value的元素
public boolean containsValue(Object value) {
Node<K, V>[] tab;
V v;
if((tab = table) != null && size>0) {
for(Node<K, V> e : tab) {
for(; e != null; e = e.next) {
if((v = e.value) == value || (value != null && value.equals(v))) {
return true;
}
}
}
}
return false;
}
/*▲ 包含查询 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 视图 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own {@code remove} operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* {@code Iterator.remove}, {@code Set.remove},
* {@code removeAll}, {@code retainAll}, and {@code clear}
* operations. It does not support the {@code add} or {@code addAll}
* operations.
*
* @return a set view of the keys contained in this map
*/
// 获取HashMap中key的集合
public Set<K> keySet() {
Set<K> ks = keySet;
if(ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own {@code remove} operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Collection.remove}, {@code removeAll},
* {@code retainAll} and {@code clear} operations. It does not
* support the {@code add} or {@code addAll} operations.
*
* @return a view of the values contained in this map
*/
// 获取HashMap中value的集合
public Collection<V> values() {
Collection<V> vs = values;
if(vs == null) {
vs = new Values();
values = vs;
}
return vs;
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own {@code remove} operation, or through the
* {@code setValue} operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Set.remove}, {@code removeAll}, {@code retainAll} and
* {@code clear} operations. It does not support the
* {@code add} or {@code addAll} operations.
*
* @return a set view of the mappings contained in this map
*/
// 获取HashMap中key-value对的集合
public Set<Map.Entry<K, V>> entrySet() {
Set<Map.Entry<K, V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
/*▲ 视图 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 遍历 ████████████████████████████████████████████████████████████████████████████████┓ */
// 遍历HashMap中的元素,并对其应用action操作,action的入参是元素的key和value
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Node<K, V>[] tab;
if(action == null) {
throw new NullPointerException();
}
if(size>0 && (tab = table) != null) {
int mc = modCount;
for(Node<K, V> e : tab) {
for(; e != null; e = e.next) {
action.accept(e.key, e.value);
}
}
if(modCount != mc) {
throw new ConcurrentModificationException();
}
}
}
/*▲ 遍历 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 重新映射 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* {@inheritDoc}
*
* <p>This method will, on a best-effort basis, throw a
* {@link ConcurrentModificationException} if it is detected that the
* remapping function modifies this map during computation.
*
* @throws ConcurrentModificationException if it is detected that the
* remapping function modified this map
*/
/*
* 插入/删除/替换操作,返回新值(可能为null)
* 此方法的主要意图:使用备用value和旧value创造的新value来更新旧value
*
* 注:以下流程图中,涉及到判断(◇)时,纵向代表【是】,横向代表【否】。此外,使用★代表计算。
*
* ●查找同位元素●
* |
* ↓
* ◇存在同位元素◇ --→ ★新value=备用value★ --→ ■【插入】新value■
* | 是 否
* ↓
* ◇旧value不为null --→ ★新value=备用value★ --→ ■新value【替换】旧value■
* | 是 否
* ↓
* ★新value=(旧value, 备用value)★
* |
* ↓
* ◇新value不为null◇ --→ ■【删除】同位元素■
* | 是 否
* ↓
* ■新value【替换】旧value■
*/
@Override
public V merge(K key, V bakValue, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if(bakValue == null) {
throw new NullPointerException();
}
if(remappingFunction == null) {
throw new NullPointerException();
}
int hash = hash(key);
Node<K, V>[] tab;
Node<K, V> first;
int n, i;
int binCount = 0;
TreeNode<K, V> t = null;
Node<K, V> old = null;
if(size>threshold || (tab = table) == null || (n = tab.length) == 0) {
// 初始化哈希数组,或者对哈希数组扩容,返回新的哈希数组
tab = resize();
n = tab.length;
}
// 根据给定的key和hash(由key计算而来)查找对应的(同位)元素,如果找不到,则返回null
if((first = tab[i = (n - 1) & hash]) != null) {
if(first instanceof TreeNode) {
old = (t = (TreeNode<K, V>) first).getTreeNode(hash, key);
} else {
Node<K, V> e = first;
K k;
do {
if(e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while((e = e.next) != null);
}
}
// 如果找到了同位元素
if(old != null) {
V newValue;
// 确定应用到目标元素上的新值
if(old.value != null) {
int mc = modCount;
newValue = remappingFunction.apply(old.value, bakValue);
if(mc != modCount) {
throw new ConcurrentModificationException();
}
} else {
newValue = bakValue;
}
// 如果新值不为null,直接替换旧值
if(newValue != null) {
old.value = newValue;
afterNodeAccess(old);
} else {
// 如果新值为null,则会移除该元素
removeNode(hash, key, null, false, true);
}
return newValue;
}
// 如果没找到目标元素,但是传入的value不为null,则向HashMap中插入新元素
if(bakValue != null) {
if(t != null) {
t.putTreeVal(this, tab, hash, key, bakValue);
} else {
tab[i] = newNode(hash, key, bakValue, first);
if(binCount >= TREEIFY_THRESHOLD - 1) {
treeifyBin(tab, hash);
}
}
++modCount;
++size;
afterNodeInsertion(true);
}
return bakValue;
}
/**
* {@inheritDoc}
*
* <p>This method will, on a best-effort basis, throw a
* {@link ConcurrentModificationException} if it is detected that the
* remapping function modifies this map during computation.
*
* @throws ConcurrentModificationException if it is detected that the
* remapping function modified this map
*/
/*
* 插入/删除/替换操作,返回新值(可能为null)
* 此方法的主要意图:使用key和旧value创造的新value来更新旧value
*
* 注:以下流程图中,涉及到判断(◇)时,纵向代表【是】,横向代表【否】。此外,使用★代表计算。
*
* ●查找同位元素●
* |
* ↓
* ◇存在同位元素◇ --→ ★新value=(key, null)★
* | 是 否 |
* ↓ |
* ★新value=(key, 旧value)★ |
* ├---------------------------┘
* ↓
* ◇新value不为null◇ --→ ■如果存在同位元素,则【删除】同位元素■
* | 是 否
* ↓
* ■ 存在同位元素,则新value【替换】旧value■
* ■不存在同位元素,则【插入】新value ■
*/
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if(remappingFunction == null) {
throw new NullPointerException();
}
int hash = hash(key);
Node<K, V>[] tab;
Node<K, V> first;
int n, i;
int binCount = 0;
TreeNode<K, V> t = null;
Node<K, V> old = null;
if(size>threshold || (tab = table) == null || (n = tab.length) == 0) {
// 初始化哈希数组,或者对哈希数组扩容,返回新的哈希数组
tab = resize();
n = tab.length;
}
// 根据给定的key和hash(由key计算而来)查找对应的(同位)元素,如果找不到,则返回null
if((first = tab[i = (n - 1) & hash]) != null) {
if(first instanceof TreeNode) {
old = (t = (TreeNode<K, V>) first).getTreeNode(hash, key);
} else {
Node<K, V> e = first;
K k;
do {
if(e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while((e = e.next) != null);
}
}
V oldValue = (old == null) ? null : old.value;
int mc = modCount;
// 利用key和旧的value计算一个新的value
V newValue = remappingFunction.apply(key, oldValue);
if(mc != modCount) {
throw new ConcurrentModificationException();
}
// 如果存在同位元素
if(old != null) {
if(newValue != null) {
old.value = newValue;
afterNodeAccess(old);
} else {
removeNode(hash, key, null, false, true);
}
} else if(newValue != null) {
if(t != null) {
t.putTreeVal(this, tab, hash, key, newValue);
} else {
tab[i] = newNode(hash, key, newValue, first);
if(binCount >= TREEIFY_THRESHOLD - 1) {
treeifyBin(tab, hash);
}
}
modCount = mc + 1;
++size;
afterNodeInsertion(true);
}
return newValue;
}
/**
* {@inheritDoc}
*
* <p>This method will, on a best-effort basis, throw a
* {@link ConcurrentModificationException} if it is detected that the
* remapping function modifies this map during computation.
*
* @throws ConcurrentModificationException if it is detected that the
* remapping function modified this map
*/
/*
* 删除/替换操作,返回新值(可能为null)
* 此方法的主要意图:存在同位元素,且旧value不为null时,使用key和旧value创造的新value来更新旧value
*
* 注:以下流程图中,涉及到判断(◇)时,纵向代表【是】,横向代表【否】。此外,使用★代表计算。
*
* ●查找同位元素●
* |
* ↓
* ◇存在同位元素 && 旧value不为null◇
* |