-
Notifications
You must be signed in to change notification settings - Fork 669
/
Copy pathTreeMap.java
3922 lines (3254 loc) · 159 KB
/
TreeMap.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.ObjectInputStream;
import java.io.Serializable;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/**
* A Red-Black tree based {@link NavigableMap} implementation.
* The map is sorted according to the {@linkplain Comparable natural
* ordering} of its keys, or by a {@link Comparator} provided at map
* creation time, depending on which constructor is used.
*
* <p>This implementation provides guaranteed log(n) time cost for the
* {@code containsKey}, {@code get}, {@code put} and {@code remove}
* operations. Algorithms are adaptations of those in Cormen, Leiserson, and
* Rivest's <em>Introduction to Algorithms</em>.
*
* <p>Note that the ordering maintained by a tree map, like any sorted map, and
* whether or not an explicit comparator is provided, must be <em>consistent
* with {@code equals}</em> if this sorted map is to correctly implement the
* {@code Map} interface. (See {@code Comparable} or {@code Comparator} for a
* precise definition of <em>consistent with equals</em>.) This is so because
* the {@code Map} interface is defined in terms of the {@code equals}
* operation, but a sorted map performs all key comparisons using its {@code
* compareTo} (or {@code compare}) method, so two keys that are deemed equal by
* this method are, from the standpoint of the sorted map, equal. The behavior
* of a sorted map <em>is</em> well-defined even if its ordering is
* inconsistent with {@code equals}; it just fails to obey the general contract
* of the {@code Map} interface.
*
* <p><strong>Note that this implementation is not synchronized.</strong>
* If multiple threads access a map concurrently, and at least one of the
* threads modifies the map structurally, it <em>must</em> be synchronized
* externally. (A structural modification is any operation that adds or
* deletes one or more mappings; merely changing the value associated
* with an existing key 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#synchronizedSortedMap Collections.synchronizedSortedMap}
* method. This is best done at creation time, to prevent accidental
* unsynchronized access to the map: <pre>
* SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));</pre>
*
* <p>The iterators returned by the {@code iterator} method of the collections
* returned by all of this class's "collection view methods" are
* <em>fail-fast</em>: 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: <em>the fail-fast behavior of iterators
* should be used only to detect bugs.</em>
*
* <p>All {@code Map.Entry} pairs returned by methods in this class
* and its views represent snapshots of mappings at the time they were
* produced. They do <strong>not</strong> support the {@code Entry.setValue}
* method. (Note however that it is possible to change mappings in the
* associated map using {@code put}.)
*
* <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 Josh Bloch and Doug Lea
* @see Map
* @see HashMap
* @see Hashtable
* @see Comparable
* @see Comparator
* @see Collection
* @since 1.2
*/
/*
* TreeMap结构:红黑树(没有哈希数组,这一点不同于HashMap)。key不能为null,但value可以为null
*
* TreeMap中的key有序,可以升序也可以降序
*
* key的排序方式依赖于外部比较器(优先使用)和内部比较器
*
* 注:
* 在无特殊说明的情形下,注释中提到的遍历都是指中序遍历当前的Map
* 至于中序序列是递增还是递减,则由Map的特性决定(可能是升序Map,也可能是降序Map)
*
* 术语约定:
* TreeMap中包含两种子视图:AscendingSubMap和DescendingSubMap
* 在TreeMap及其子视图中,当提到靠左、靠前、靠右、靠后的元素时,指的是在正序Map下的排序
* 而正序Map或逆序Map是由相关的内部比较器和外部比较器决定的
*/
public class TreeMap<K, V> extends AbstractMap<K, V> implements NavigableMap<K, V>, Cloneable, Serializable {
/**
* The comparator used to maintain order in this tree map, or null if it uses the natural ordering of its keys.
*
* @serial
*/
private final Comparator<? super K> comparator; // TreeMap中的外部比较器,如果不为null,会优先使用
private transient Entry<K, V> root; // 红黑树的根(TreeMap根结点)
// 代表红黑树结点颜色的常量
private static final boolean RED = false;
private static final boolean BLACK = true;
/**
* Fields initialized to contain an instance of the entry set view
* the first time this view is requested. Views are stateless, so
* there's no reason to create more than one.
*/
private transient EntrySet entrySet; // 当前Map中key-value对的集合
private transient KeySet<K> navigableKeySet; // 当前Map中的key的集合
private transient NavigableMap<K, V> descendingMap; // 【逆序】Map(实质是对当前Map实例的一个【逆序】包装)
/**
* The number of entries in the tree
*/
private transient int size = 0; // TreeMap中的元素数量
/**
* The number of structural modifications to the tree.
*/
private transient int modCount = 0; // 记录TreeMap结构的修改次数
/**
* Dummy value serving as unmatchable fence key for unbounded SubMapIterators
*/
private static final Object UNBOUNDED = new Object();
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Constructs a new, empty tree map, using the natural ordering of its
* keys. All keys inserted into the map must implement the {@link
* Comparable} interface. Furthermore, all such keys must be
* <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
* a {@code ClassCastException} for any keys {@code k1} and
* {@code k2} in the map. If the user attempts to put a key into the
* map that violates this constraint (for example, the user attempts to
* put a string key into a map whose keys are integers), the
* {@code put(Object key, Object value)} call will throw a
* {@code ClassCastException}.
*/
public TreeMap() {
comparator = null;
}
/**
* Constructs a new, empty tree map, ordered according to the given
* comparator. All keys inserted into the map must be <em>mutually
* comparable</em> by the given comparator: {@code comparator.compare(k1,
* k2)} must not throw a {@code ClassCastException} for any keys
* {@code k1} and {@code k2} in the map. If the user attempts to put
* a key into the map that violates this constraint, the {@code put(Object
* key, Object value)} call will throw a
* {@code ClassCastException}.
*
* @param comparator the comparator that will be used to order this map.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the keys will be used.
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
/**
* Constructs a new tree map containing the same mappings as the given
* map, ordered according to the <em>natural ordering</em> of its keys.
* All keys inserted into the new map must implement the {@link
* Comparable} interface. Furthermore, all such keys must be
* <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
* a {@code ClassCastException} for any keys {@code k1} and
* {@code k2} in the map. This method runs in n*log(n) time.
*
* @param m the map whose mappings are to be placed in this map
*
* @throws ClassCastException if the keys in m are not {@link Comparable},
* or are not mutually comparable
* @throws NullPointerException if the specified map is null
*/
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
/**
* Constructs a new tree map containing the same mappings and
* using the same ordering as the specified sorted map. This
* method runs in linear time.
*
* @param m the sorted map whose mappings are to be placed in this map,
* and whose comparator is to be used to sort this map
*
* @throws NullPointerException if the specified map is null
*/
public TreeMap(SortedMap<K, ? extends V> m) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch(java.io.IOException | ClassNotFoundException cannotHappen) {
}
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 存值 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* 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}.)
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
/*
* 向当前Map中存储一个key-value对,返回值代表该位置存储之前的值
*
* 如果外部比较器comparator有效,则允许key为null
* 否则,key不能为null,且需要实现内部比较器Comparable接口
*/
public V put(K key, V value) {
Entry<K, V> t = root;
// 如果根结点为null,说明是首个结点
if(t == null) {
// 这里使用compare起到了校验作用
compare(key, key); // type (and possibly null) check
// 创建一个红黑树结点
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K, V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
/* 查找同位元素,如果找到,直接覆盖 */
// 如果存在外部比较器
if(cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if(cmp<0) {
t = t.left;
} else if(cmp>0) {
t = t.right;
} else {
return t.setValue(value);
}
} while(t != null);
// 如果不存在外部比较器,则要求key实现内部比较器Comparable接口
} else {
if(key == null) {
throw new NullPointerException();
}
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if(cmp<0) {
t = t.left;
} else if(cmp>0) {
t = t.right;
} else {
return t.setValue(value);
}
} while(t != null);
}
/* 至此,说明没找到同位元素,需要新建一个元素插入到红黑树中 */
Entry<K, V> e = new Entry<>(key, value, parent);
if(cmp<0) {
parent.left = e;
} else {
parent.right = e;
}
// 将元素e插入到红黑树后,可能会破坏其平衡性,所以这里需要做出调整,保持红黑树的平衡
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
/**
* Copies all of the mappings from the specified map to this map.
* These mappings replace any mappings that this map had for any
* of the keys currently in the specified map.
*
* @param map mappings to be stored in this map
*
* @throws ClassCastException if the class of a key or value in
* the specified map prevents it from being stored in this map
* @throws NullPointerException if the specified map is null or
* the specified map contains a null key and this map does not
* permit null keys
*/
// 将指定Map中的元素存入到当前Map(允许覆盖)
public void putAll(Map<? extends K, ? extends V> map) {
int mapSize = map.size();
if(size == 0 && mapSize != 0 && map instanceof SortedMap) {
Comparator<?> c = ((SortedMap<?, ?>) map).comparator();
if(c == comparator || (c != null && c.equals(comparator))) {
++modCount;
try {
buildFromSorted(mapSize, map.entrySet().iterator(), null, null);
} catch(IOException | ClassNotFoundException cannotHappen) {
}
return;
}
}
super.putAll(map);
}
/*▲ 存值 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 取值 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* 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} compares
* equal to {@code k} according to the map's ordering, 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 <em>necessarily</em>
* 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.
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
// 查找key对应的元素的值,如果不存在该元素,则返回null值
public V get(Object key) {
// 查找key对应的元素
Entry<K, V> p = getEntry(key);
return (p == null ? null : p.value);
}
/*▲ 取值 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 移除 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Removes the mapping for this key from this TreeMap if present.
*
* @param key key for which mapping should be removed
*
* @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}.)
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
// 查找key对应的元素,并移除该元素
public V remove(Object key) {
Entry<K, V> p = getEntry(key);
if(p == null) {
return null;
}
V oldValue = p.value;
// 将元素从红黑树中移除
deleteEntry(p);
return oldValue;
}
/**
* Removes all of the mappings from this map.
* The map will be empty after this call returns.
*/
// 清空当前Map
public void clear() {
modCount++;
size = 0;
root = null;
}
/*▲ 移除 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 替换 ████████████████████████████████████████████████████████████████████████████████┓ */
// 将拥有指定key的元素的值替换为newValue,并返回刚刚替换的元素的值(替换失败返回null)
@Override
public V replace(K key, V newValue) {
// 查找key对应的元素
Entry<K, V> p = getEntry(key);
if(p != null) {
V oldValue = p.value;
p.value = newValue;
return oldValue;
}
return null;
}
// 将拥有指定key和oldValue的元素的值替换为newValue,返回值表示是否成功替换
@Override
public boolean replace(K key, V oldValue, V newValue) {
// 查找key对应的元素
Entry<K, V> p = getEntry(key);
if(p != null && Objects.equals(oldValue, p.value)) {
p.value = newValue;
return true;
}
return false;
}
// 替换当前当前Map中的所有元素,替换策略由function决定,function的入参是元素的key和value,出参作为新值
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Objects.requireNonNull(function);
int expectedModCount = modCount;
for(Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
e.value = function.apply(e.key, e.value);
if(expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
}
/*▲ 替换 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 包含查询 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns {@code true} if this map contains a mapping for the specified
* key.
*
* @param key key whose presence in this map is to be tested
*
* @return {@code true} if this map contains a mapping for the
* specified key
*
* @throws ClassCastException if the specified key cannot be compared
* with the keys currently in the map
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
*/
// 判断当前Map中是否存在指定key的元素
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
/**
* Returns {@code true} if this map maps one or more keys to the
* specified value. More formally, returns {@code true} if and only if
* this map contains at least one mapping to a value {@code v} such
* that {@code (value==null ? v==null : value.equals(v))}. This
* operation will probably require time linear in the map size for
* most implementations.
*
* @param value value whose presence in this map is to be tested
*
* @return {@code true} if a mapping to {@code value} exists;
* {@code false} otherwise
*
* @since 1.2
*/
// 判断当前Map中是否存在指定value的元素
public boolean containsValue(Object value) {
for(Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
if(valEquals(value, e.value)) {
return true;
}
}
return false;
}
/*▲ 包含查询 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 视图 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a {@link Set} view of the keys contained in this map.
*
* <p>The set's iterator returns the keys in ascending order.
* The set's spliterator is
* <em><a href="Spliterator.html#binding">late-binding</a></em>,
* <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED}
* and {@link Spliterator#ORDERED} with an encounter order that is ascending
* key order. The spliterator's comparator (see
* {@link java.util.Spliterator#getComparator()}) is {@code null} if
* the tree map's comparator (see {@link #comparator()}) is {@code null}.
* Otherwise, the spliterator's comparator is the same as or imposes the
* same total ordering as the tree map's comparator.
*
* <p>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.
*/
// 获取当前Map中key的集合
public Set<K> keySet() {
return navigableKeySet();
}
/**
* Returns a {@link Collection} view of the values contained in this map.
*
* <p>The collection's iterator returns the values in ascending order
* of the corresponding keys. The collection's spliterator is
* <em><a href="Spliterator.html#binding">late-binding</a></em>,
* <em>fail-fast</em>, and additionally reports {@link Spliterator#ORDERED}
* with an encounter order that is ascending order of the corresponding
* keys.
*
* <p>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.
*/
// 获取当前Map中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.
*
* <p>The set's iterator returns the entries in ascending key order. The
* set's spliterator is
* <em><a href="Spliterator.html#binding">late-binding</a></em>,
* <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED} and
* {@link Spliterator#ORDERED} with an encounter order that is ascending key
* order.
*
* <p>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.
*/
// 获取当前Map中key-value对的集合
public Set<Map.Entry<K, V>> entrySet() {
EntrySet es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
/*▲ 视图 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 遍历 ████████████████████████████████████████████████████████████████████████████████┓ */
// 遍历TreeMap中的元素,并对其应用action操作,action的入参是元素的key和value
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
int expectedModCount = modCount;
for(Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
action.accept(e.key, e.value);
if(expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
}
/*▲ 遍历 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ NavigableMap/SortedMap █████████████████████████████████████████████████████████████┓ */
// 获取当前Map的外部比较器Comparator
public Comparator<? super K> comparator() {
return comparator;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
// 返回遍历当前Map时的首个结点的key
public K firstKey() {
return key(getFirstEntry());
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
// 返回遍历当前Map时的末尾结点的key
public K lastKey() {
return key(getLastEntry());
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 〖前驱〗获取一个key,该key是遍历当前Map时形参key的前驱
public K lowerKey(K key) {
return keyOrNull(getLowerEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 〖后继〗获取一个key,该key是遍历当前Map时形参key的后继
public K higherKey(K key) {
return keyOrNull(getHigherEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 【前驱】获取一个key,该key是遍历当前Map时形参key的前驱(包括key本身)
public K floorKey(K key) {
return keyOrNull(getFloorEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 【后继】获取一个key,该key是遍历当前Map时形参key的后继(包括key本身)
public K ceilingKey(K key) {
return keyOrNull(getCeilingEntry(key));
}
/**
* @since 1.6
*/
// 获取遍历当前Map时的首个结点,然后将其包装为只读版本的Entry
public Map.Entry<K, V> firstEntry() {
return exportEntry(getFirstEntry());
}
/**
* @since 1.6
*/
// 返回遍历当前Map时的末尾结点,然后将其包装为只读版本的Entry
public Map.Entry<K, V> lastEntry() {
return exportEntry(getLastEntry());
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 〖前驱〗获取一个结点并将其包装为只读版本的Entry,该结点包含的key,是遍历当前Map时形参k的前驱
public Map.Entry<K, V> lowerEntry(K key) {
return exportEntry(getLowerEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 〖后继〗获取一个结点并将其包装为只读版本的Entry,该结点包含的key,是遍历当前Map时形参k的后继
public Map.Entry<K, V> higherEntry(K key) {
return exportEntry(getHigherEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 【前驱】获取一个结点并将其包装为只读版本的Entry,该结点包含的key,是遍历当前Map时形参k的前驱(包括k本身)
public Map.Entry<K, V> floorEntry(K key) {
return exportEntry(getFloorEntry(key));
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if the specified key is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @since 1.6
*/
// 【后继】获取一个结点并将其包装为只读版本的Entry,该结点包含的key,是遍历当前Map时形参k的后继(包括k本身)
public Map.Entry<K, V> ceilingEntry(K key) {
return exportEntry(getCeilingEntry(key));
}
/**
* @since 1.6
*/
// 移除遍历当前Map时的首个结点,并将其包装为只读版本的Entry后返回
public Map.Entry<K, V> pollFirstEntry() {
Entry<K, V> p = getFirstEntry();
if(p != null) {
deleteEntry(p);
}
return exportEntry(p);
}
/**
* @since 1.6
*/
// 移除遍历当前Map时的末尾结点,并将其包装为只读版本的Entry后返回
public Map.Entry<K, V> pollLastEntry() {
Entry<K, V> p = getLastEntry();
if(p != null) {
deleteEntry(p);
}
return exportEntry(p);
}
/**
* @since 1.6
*/
// 获取当前Map中的key的集合
public NavigableSet<K> navigableKeySet() {
KeySet<K> nks = navigableKeySet;
return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
}
/**
* @since 1.6
*/
// 获取【逆序】Map中的key的集合
public NavigableSet<K> descendingKeySet() {
return descendingMap().navigableKeySet();
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} or {@code toKey} is
* null and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
*/
// 获取【理论区间】为[fromKey, toKey)的SubMap
public SortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} or {@code toKey} is
* null and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
// 获取【理论区间】为〖fromKey, toKey〗的SubMap,区间下限/上限是否为闭区间由fromInclusive和toInclusive参数决定
public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
return new AscendingSubMap<>(this, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code toKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
*/
// 获取【理论区间】上限为toKey(不包含)的SubMap
public SortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code toKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
// 获取【理论区间】上限为toKey的SubMap,区间上限是否为闭区间由inclusive参数决定
public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
return new AscendingSubMap<>(this, true, null, true, false, toKey, inclusive);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
*/
// 获取【理论区间】下限为fromKey(包含)的SubMap
public SortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
/**
* @throws ClassCastException {@inheritDoc}
* @throws NullPointerException if {@code fromKey} is null
* and this map uses natural ordering, or its comparator
* does not permit null keys
* @throws IllegalArgumentException {@inheritDoc}
* @since 1.6
*/
// 获取【理论区间】下限为fromKey的SubMap,区间下限是否为闭区间由inclusive参数决定
public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
return new AscendingSubMap<>(this, false, fromKey, inclusive, true, null, true);
}
/**
* @since 1.6
*/
// 获取【逆序】Map(实质是对当前Map实例的一个【逆序】包装)
public NavigableMap<K, V> descendingMap() {
NavigableMap<K, V> km = descendingMap;
return (km != null) ? km : (descendingMap = new DescendingSubMap<>(this, true, null, true, true, null, true));
}
/*▲ NavigableMap/SortedMap █████████████████████████████████████████████████████████████┛ */
/*▼ 杂项 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
// 获取当前Map中的元素数量
public int size() {
return size;
}
/*▲ 杂项 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 序列化 ████████████████████████████████████████████████████████████████████████████████┓ */
private static final long serialVersionUID = 919286545866124006L;
/**
* Save the state of the {@code TreeMap} instance to a stream (i.e.,
* serialize it).
*
* @serialData The <em>size</em> of the TreeMap (the number of key-value
* mappings) is emitted (int), followed by the key (Object)
* and value (Object) for each key-value mapping represented
* by the TreeMap. The key-value mappings are emitted in
* key-order (as determined by the TreeMap's Comparator,
* or by the keys' natural ordering if the TreeMap has no
* Comparator).
*/
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
// Write out the Comparator and any hidden stuff
s.defaultWriteObject();
// Write out size (number of Mappings)
s.writeInt(size);