Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/java.base/share/classes/java/util/HashMap.java
67794 views
1
/*
2
* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.util;
27
28
import java.io.IOException;
29
import java.io.InvalidObjectException;
30
import java.io.ObjectInputStream;
31
import java.io.Serializable;
32
import java.lang.reflect.ParameterizedType;
33
import java.lang.reflect.Type;
34
import java.util.function.BiConsumer;
35
import java.util.function.BiFunction;
36
import java.util.function.Consumer;
37
import java.util.function.Function;
38
import jdk.internal.access.SharedSecrets;
39
40
/**
41
* Hash table based implementation of the {@code Map} interface. This
42
* implementation provides all of the optional map operations, and permits
43
* {@code null} values and the {@code null} key. (The {@code HashMap}
44
* class is roughly equivalent to {@code Hashtable}, except that it is
45
* unsynchronized and permits nulls.) This class makes no guarantees as to
46
* the order of the map; in particular, it does not guarantee that the order
47
* will remain constant over time.
48
*
49
* <p>This implementation provides constant-time performance for the basic
50
* operations ({@code get} and {@code put}), assuming the hash function
51
* disperses the elements properly among the buckets. Iteration over
52
* collection views requires time proportional to the "capacity" of the
53
* {@code HashMap} instance (the number of buckets) plus its size (the number
54
* of key-value mappings). Thus, it's very important not to set the initial
55
* capacity too high (or the load factor too low) if iteration performance is
56
* important.
57
*
58
* <p>An instance of {@code HashMap} has two parameters that affect its
59
* performance: <i>initial capacity</i> and <i>load factor</i>. The
60
* <i>capacity</i> is the number of buckets in the hash table, and the initial
61
* capacity is simply the capacity at the time the hash table is created. The
62
* <i>load factor</i> is a measure of how full the hash table is allowed to
63
* get before its capacity is automatically increased. When the number of
64
* entries in the hash table exceeds the product of the load factor and the
65
* current capacity, the hash table is <i>rehashed</i> (that is, internal data
66
* structures are rebuilt) so that the hash table has approximately twice the
67
* number of buckets.
68
*
69
* <p>As a general rule, the default load factor (.75) offers a good
70
* tradeoff between time and space costs. Higher values decrease the
71
* space overhead but increase the lookup cost (reflected in most of
72
* the operations of the {@code HashMap} class, including
73
* {@code get} and {@code put}). The expected number of entries in
74
* the map and its load factor should be taken into account when
75
* setting its initial capacity, so as to minimize the number of
76
* rehash operations. If the initial capacity is greater than the
77
* maximum number of entries divided by the load factor, no rehash
78
* operations will ever occur.
79
*
80
* <p>If many mappings are to be stored in a {@code HashMap}
81
* instance, creating it with a sufficiently large capacity will allow
82
* the mappings to be stored more efficiently than letting it perform
83
* automatic rehashing as needed to grow the table. Note that using
84
* many keys with the same {@code hashCode()} is a sure way to slow
85
* down performance of any hash table. To ameliorate impact, when keys
86
* are {@link Comparable}, this class may use comparison order among
87
* keys to help break ties.
88
*
89
* <p><strong>Note that this implementation is not synchronized.</strong>
90
* If multiple threads access a hash map concurrently, and at least one of
91
* the threads modifies the map structurally, it <i>must</i> be
92
* synchronized externally. (A structural modification is any operation
93
* that adds or deletes one or more mappings; merely changing the value
94
* associated with a key that an instance already contains is not a
95
* structural modification.) This is typically accomplished by
96
* synchronizing on some object that naturally encapsulates the map.
97
*
98
* If no such object exists, the map should be "wrapped" using the
99
* {@link Collections#synchronizedMap Collections.synchronizedMap}
100
* method. This is best done at creation time, to prevent accidental
101
* unsynchronized access to the map:<pre>
102
* Map m = Collections.synchronizedMap(new HashMap(...));</pre>
103
*
104
* <p>The iterators returned by all of this class's "collection view methods"
105
* are <i>fail-fast</i>: if the map is structurally modified at any time after
106
* the iterator is created, in any way except through the iterator's own
107
* {@code remove} method, the iterator will throw a
108
* {@link ConcurrentModificationException}. Thus, in the face of concurrent
109
* modification, the iterator fails quickly and cleanly, rather than risking
110
* arbitrary, non-deterministic behavior at an undetermined time in the
111
* future.
112
*
113
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
114
* as it is, generally speaking, impossible to make any hard guarantees in the
115
* presence of unsynchronized concurrent modification. Fail-fast iterators
116
* throw {@code ConcurrentModificationException} on a best-effort basis.
117
* Therefore, it would be wrong to write a program that depended on this
118
* exception for its correctness: <i>the fail-fast behavior of iterators
119
* should be used only to detect bugs.</i>
120
*
121
* <p>This class is a member of the
122
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
123
* Java Collections Framework</a>.
124
*
125
* @param <K> the type of keys maintained by this map
126
* @param <V> the type of mapped values
127
*
128
* @author Doug Lea
129
* @author Josh Bloch
130
* @author Arthur van Hoff
131
* @author Neal Gafter
132
* @see Object#hashCode()
133
* @see Collection
134
* @see Map
135
* @see TreeMap
136
* @see Hashtable
137
* @since 1.2
138
*/
139
public class HashMap<K,V> extends AbstractMap<K,V>
140
implements Map<K,V>, Cloneable, Serializable {
141
142
@java.io.Serial
143
private static final long serialVersionUID = 362498820763181265L;
144
145
/*
146
* Implementation notes.
147
*
148
* This map usually acts as a binned (bucketed) hash table, but
149
* when bins get too large, they are transformed into bins of
150
* TreeNodes, each structured similarly to those in
151
* java.util.TreeMap. Most methods try to use normal bins, but
152
* relay to TreeNode methods when applicable (simply by checking
153
* instanceof a node). Bins of TreeNodes may be traversed and
154
* used like any others, but additionally support faster lookup
155
* when overpopulated. However, since the vast majority of bins in
156
* normal use are not overpopulated, checking for existence of
157
* tree bins may be delayed in the course of table methods.
158
*
159
* Tree bins (i.e., bins whose elements are all TreeNodes) are
160
* ordered primarily by hashCode, but in the case of ties, if two
161
* elements are of the same "class C implements Comparable<C>",
162
* type then their compareTo method is used for ordering. (We
163
* conservatively check generic types via reflection to validate
164
* this -- see method comparableClassFor). The added complexity
165
* of tree bins is worthwhile in providing worst-case O(log n)
166
* operations when keys either have distinct hashes or are
167
* orderable, Thus, performance degrades gracefully under
168
* accidental or malicious usages in which hashCode() methods
169
* return values that are poorly distributed, as well as those in
170
* which many keys share a hashCode, so long as they are also
171
* Comparable. (If neither of these apply, we may waste about a
172
* factor of two in time and space compared to taking no
173
* precautions. But the only known cases stem from poor user
174
* programming practices that are already so slow that this makes
175
* little difference.)
176
*
177
* Because TreeNodes are about twice the size of regular nodes, we
178
* use them only when bins contain enough nodes to warrant use
179
* (see TREEIFY_THRESHOLD). And when they become too small (due to
180
* removal or resizing) they are converted back to plain bins. In
181
* usages with well-distributed user hashCodes, tree bins are
182
* rarely used. Ideally, under random hashCodes, the frequency of
183
* nodes in bins follows a Poisson distribution
184
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
185
* parameter of about 0.5 on average for the default resizing
186
* threshold of 0.75, although with a large variance because of
187
* resizing granularity. Ignoring variance, the expected
188
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
189
* factorial(k)). The first values are:
190
*
191
* 0: 0.60653066
192
* 1: 0.30326533
193
* 2: 0.07581633
194
* 3: 0.01263606
195
* 4: 0.00157952
196
* 5: 0.00015795
197
* 6: 0.00001316
198
* 7: 0.00000094
199
* 8: 0.00000006
200
* more: less than 1 in ten million
201
*
202
* The root of a tree bin is normally its first node. However,
203
* sometimes (currently only upon Iterator.remove), the root might
204
* be elsewhere, but can be recovered following parent links
205
* (method TreeNode.root()).
206
*
207
* All applicable internal methods accept a hash code as an
208
* argument (as normally supplied from a public method), allowing
209
* them to call each other without recomputing user hashCodes.
210
* Most internal methods also accept a "tab" argument, that is
211
* normally the current table, but may be a new or old one when
212
* resizing or converting.
213
*
214
* When bin lists are treeified, split, or untreeified, we keep
215
* them in the same relative access/traversal order (i.e., field
216
* Node.next) to better preserve locality, and to slightly
217
* simplify handling of splits and traversals that invoke
218
* iterator.remove. When using comparators on insertion, to keep a
219
* total ordering (or as close as is required here) across
220
* rebalancings, we compare classes and identityHashCodes as
221
* tie-breakers.
222
*
223
* The use and transitions among plain vs tree modes is
224
* complicated by the existence of subclass LinkedHashMap. See
225
* below for hook methods defined to be invoked upon insertion,
226
* removal and access that allow LinkedHashMap internals to
227
* otherwise remain independent of these mechanics. (This also
228
* requires that a map instance be passed to some utility methods
229
* that may create new nodes.)
230
*
231
* The concurrent-programming-like SSA-based coding style helps
232
* avoid aliasing errors amid all of the twisty pointer operations.
233
*/
234
235
/**
236
* The default initial capacity - MUST be a power of two.
237
*/
238
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
239
240
/**
241
* The maximum capacity, used if a higher value is implicitly specified
242
* by either of the constructors with arguments.
243
* MUST be a power of two <= 1<<30.
244
*/
245
static final int MAXIMUM_CAPACITY = 1 << 30;
246
247
/**
248
* The load factor used when none specified in constructor.
249
*/
250
static final float DEFAULT_LOAD_FACTOR = 0.75f;
251
252
/**
253
* The bin count threshold for using a tree rather than list for a
254
* bin. Bins are converted to trees when adding an element to a
255
* bin with at least this many nodes. The value must be greater
256
* than 2 and should be at least 8 to mesh with assumptions in
257
* tree removal about conversion back to plain bins upon
258
* shrinkage.
259
*/
260
static final int TREEIFY_THRESHOLD = 8;
261
262
/**
263
* The bin count threshold for untreeifying a (split) bin during a
264
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
265
* most 6 to mesh with shrinkage detection under removal.
266
*/
267
static final int UNTREEIFY_THRESHOLD = 6;
268
269
/**
270
* The smallest table capacity for which bins may be treeified.
271
* (Otherwise the table is resized if too many nodes in a bin.)
272
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
273
* between resizing and treeification thresholds.
274
*/
275
static final int MIN_TREEIFY_CAPACITY = 64;
276
277
/**
278
* Basic hash bin node, used for most entries. (See below for
279
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
280
*/
281
static class Node<K,V> implements Map.Entry<K,V> {
282
final int hash;
283
final K key;
284
V value;
285
Node<K,V> next;
286
287
Node(int hash, K key, V value, Node<K,V> next) {
288
this.hash = hash;
289
this.key = key;
290
this.value = value;
291
this.next = next;
292
}
293
294
public final K getKey() { return key; }
295
public final V getValue() { return value; }
296
public final String toString() { return key + "=" + value; }
297
298
public final int hashCode() {
299
return Objects.hashCode(key) ^ Objects.hashCode(value);
300
}
301
302
public final V setValue(V newValue) {
303
V oldValue = value;
304
value = newValue;
305
return oldValue;
306
}
307
308
public final boolean equals(Object o) {
309
if (o == this)
310
return true;
311
312
return o instanceof Map.Entry<?, ?> e
313
&& Objects.equals(key, e.getKey())
314
&& Objects.equals(value, e.getValue());
315
}
316
}
317
318
/* ---------------- Static utilities -------------- */
319
320
/**
321
* Computes key.hashCode() and spreads (XORs) higher bits of hash
322
* to lower. Because the table uses power-of-two masking, sets of
323
* hashes that vary only in bits above the current mask will
324
* always collide. (Among known examples are sets of Float keys
325
* holding consecutive whole numbers in small tables.) So we
326
* apply a transform that spreads the impact of higher bits
327
* downward. There is a tradeoff between speed, utility, and
328
* quality of bit-spreading. Because many common sets of hashes
329
* are already reasonably distributed (so don't benefit from
330
* spreading), and because we use trees to handle large sets of
331
* collisions in bins, we just XOR some shifted bits in the
332
* cheapest possible way to reduce systematic lossage, as well as
333
* to incorporate impact of the highest bits that would otherwise
334
* never be used in index calculations because of table bounds.
335
*/
336
static final int hash(Object key) {
337
int h;
338
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
339
}
340
341
/**
342
* Returns x's Class if it is of the form "class C implements
343
* Comparable<C>", else null.
344
*/
345
static Class<?> comparableClassFor(Object x) {
346
if (x instanceof Comparable) {
347
Class<?> c; Type[] ts, as; ParameterizedType p;
348
if ((c = x.getClass()) == String.class) // bypass checks
349
return c;
350
if ((ts = c.getGenericInterfaces()) != null) {
351
for (Type t : ts) {
352
if ((t instanceof ParameterizedType) &&
353
((p = (ParameterizedType) t).getRawType() ==
354
Comparable.class) &&
355
(as = p.getActualTypeArguments()) != null &&
356
as.length == 1 && as[0] == c) // type arg is c
357
return c;
358
}
359
}
360
}
361
return null;
362
}
363
364
/**
365
* Returns k.compareTo(x) if x matches kc (k's screened comparable
366
* class), else 0.
367
*/
368
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
369
static int compareComparables(Class<?> kc, Object k, Object x) {
370
return (x == null || x.getClass() != kc ? 0 :
371
((Comparable)k).compareTo(x));
372
}
373
374
/**
375
* Returns a power of two size for the given target capacity.
376
*/
377
static final int tableSizeFor(int cap) {
378
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
379
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
380
}
381
382
/* ---------------- Fields -------------- */
383
384
/**
385
* The table, initialized on first use, and resized as
386
* necessary. When allocated, length is always a power of two.
387
* (We also tolerate length zero in some operations to allow
388
* bootstrapping mechanics that are currently not needed.)
389
*/
390
transient Node<K,V>[] table;
391
392
/**
393
* Holds cached entrySet(). Note that AbstractMap fields are used
394
* for keySet() and values().
395
*/
396
transient Set<Map.Entry<K,V>> entrySet;
397
398
/**
399
* The number of key-value mappings contained in this map.
400
*/
401
transient int size;
402
403
/**
404
* The number of times this HashMap has been structurally modified
405
* Structural modifications are those that change the number of mappings in
406
* the HashMap or otherwise modify its internal structure (e.g.,
407
* rehash). This field is used to make iterators on Collection-views of
408
* the HashMap fail-fast. (See ConcurrentModificationException).
409
*/
410
transient int modCount;
411
412
/**
413
* The next size value at which to resize (capacity * load factor).
414
*
415
* @serial
416
*/
417
// (The javadoc description is true upon serialization.
418
// Additionally, if the table array has not been allocated, this
419
// field holds the initial array capacity, or zero signifying
420
// DEFAULT_INITIAL_CAPACITY.)
421
int threshold;
422
423
/**
424
* The load factor for the hash table.
425
*
426
* @serial
427
*/
428
final float loadFactor;
429
430
/* ---------------- Public operations -------------- */
431
432
/**
433
* Constructs an empty {@code HashMap} with the specified initial
434
* capacity and load factor.
435
*
436
* @param initialCapacity the initial capacity
437
* @param loadFactor the load factor
438
* @throws IllegalArgumentException if the initial capacity is negative
439
* or the load factor is nonpositive
440
*/
441
public HashMap(int initialCapacity, float loadFactor) {
442
if (initialCapacity < 0)
443
throw new IllegalArgumentException("Illegal initial capacity: " +
444
initialCapacity);
445
if (initialCapacity > MAXIMUM_CAPACITY)
446
initialCapacity = MAXIMUM_CAPACITY;
447
if (loadFactor <= 0 || Float.isNaN(loadFactor))
448
throw new IllegalArgumentException("Illegal load factor: " +
449
loadFactor);
450
this.loadFactor = loadFactor;
451
this.threshold = tableSizeFor(initialCapacity);
452
}
453
454
/**
455
* Constructs an empty {@code HashMap} with the specified initial
456
* capacity and the default load factor (0.75).
457
*
458
* @param initialCapacity the initial capacity.
459
* @throws IllegalArgumentException if the initial capacity is negative.
460
*/
461
public HashMap(int initialCapacity) {
462
this(initialCapacity, DEFAULT_LOAD_FACTOR);
463
}
464
465
/**
466
* Constructs an empty {@code HashMap} with the default initial capacity
467
* (16) and the default load factor (0.75).
468
*/
469
public HashMap() {
470
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
471
}
472
473
/**
474
* Constructs a new {@code HashMap} with the same mappings as the
475
* specified {@code Map}. The {@code HashMap} is created with
476
* default load factor (0.75) and an initial capacity sufficient to
477
* hold the mappings in the specified {@code Map}.
478
*
479
* @param m the map whose mappings are to be placed in this map
480
* @throws NullPointerException if the specified map is null
481
*/
482
public HashMap(Map<? extends K, ? extends V> m) {
483
this.loadFactor = DEFAULT_LOAD_FACTOR;
484
putMapEntries(m, false);
485
}
486
487
/**
488
* Implements Map.putAll and Map constructor.
489
*
490
* @param m the map
491
* @param evict false when initially constructing this map, else
492
* true (relayed to method afterNodeInsertion).
493
*/
494
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
495
int s = m.size();
496
if (s > 0) {
497
if (table == null) { // pre-size
498
float ft = ((float)s / loadFactor) + 1.0F;
499
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
500
(int)ft : MAXIMUM_CAPACITY);
501
if (t > threshold)
502
threshold = tableSizeFor(t);
503
} else {
504
// Because of linked-list bucket constraints, we cannot
505
// expand all at once, but can reduce total resize
506
// effort by repeated doubling now vs later
507
while (s > threshold && table.length < MAXIMUM_CAPACITY)
508
resize();
509
}
510
511
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
512
K key = e.getKey();
513
V value = e.getValue();
514
putVal(hash(key), key, value, false, evict);
515
}
516
}
517
}
518
519
/**
520
* Returns the number of key-value mappings in this map.
521
*
522
* @return the number of key-value mappings in this map
523
*/
524
public int size() {
525
return size;
526
}
527
528
/**
529
* Returns {@code true} if this map contains no key-value mappings.
530
*
531
* @return {@code true} if this map contains no key-value mappings
532
*/
533
public boolean isEmpty() {
534
return size == 0;
535
}
536
537
/**
538
* Returns the value to which the specified key is mapped,
539
* or {@code null} if this map contains no mapping for the key.
540
*
541
* <p>More formally, if this map contains a mapping from a key
542
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
543
* key.equals(k))}, then this method returns {@code v}; otherwise
544
* it returns {@code null}. (There can be at most one such mapping.)
545
*
546
* <p>A return value of {@code null} does not <i>necessarily</i>
547
* indicate that the map contains no mapping for the key; it's also
548
* possible that the map explicitly maps the key to {@code null}.
549
* The {@link #containsKey containsKey} operation may be used to
550
* distinguish these two cases.
551
*
552
* @see #put(Object, Object)
553
*/
554
public V get(Object key) {
555
Node<K,V> e;
556
return (e = getNode(key)) == null ? null : e.value;
557
}
558
559
/**
560
* Implements Map.get and related methods.
561
*
562
* @param key the key
563
* @return the node, or null if none
564
*/
565
final Node<K,V> getNode(Object key) {
566
Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
567
if ((tab = table) != null && (n = tab.length) > 0 &&
568
(first = tab[(n - 1) & (hash = hash(key))]) != null) {
569
if (first.hash == hash && // always check first node
570
((k = first.key) == key || (key != null && key.equals(k))))
571
return first;
572
if ((e = first.next) != null) {
573
if (first instanceof TreeNode)
574
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
575
do {
576
if (e.hash == hash &&
577
((k = e.key) == key || (key != null && key.equals(k))))
578
return e;
579
} while ((e = e.next) != null);
580
}
581
}
582
return null;
583
}
584
585
/**
586
* Returns {@code true} if this map contains a mapping for the
587
* specified key.
588
*
589
* @param key The key whose presence in this map is to be tested
590
* @return {@code true} if this map contains a mapping for the specified
591
* key.
592
*/
593
public boolean containsKey(Object key) {
594
return getNode(key) != null;
595
}
596
597
/**
598
* Associates the specified value with the specified key in this map.
599
* If the map previously contained a mapping for the key, the old
600
* value is replaced.
601
*
602
* @param key key with which the specified value is to be associated
603
* @param value value to be associated with the specified key
604
* @return the previous value associated with {@code key}, or
605
* {@code null} if there was no mapping for {@code key}.
606
* (A {@code null} return can also indicate that the map
607
* previously associated {@code null} with {@code key}.)
608
*/
609
public V put(K key, V value) {
610
return putVal(hash(key), key, value, false, true);
611
}
612
613
/**
614
* Implements Map.put and related methods.
615
*
616
* @param hash hash for key
617
* @param key the key
618
* @param value the value to put
619
* @param onlyIfAbsent if true, don't change existing value
620
* @param evict if false, the table is in creation mode.
621
* @return previous value, or null if none
622
*/
623
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
624
boolean evict) {
625
Node<K,V>[] tab; Node<K,V> p; int n, i;
626
if ((tab = table) == null || (n = tab.length) == 0)
627
n = (tab = resize()).length;
628
if ((p = tab[i = (n - 1) & hash]) == null)
629
tab[i] = newNode(hash, key, value, null);
630
else {
631
Node<K,V> e; K k;
632
if (p.hash == hash &&
633
((k = p.key) == key || (key != null && key.equals(k))))
634
e = p;
635
else if (p instanceof TreeNode)
636
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
637
else {
638
for (int binCount = 0; ; ++binCount) {
639
if ((e = p.next) == null) {
640
p.next = newNode(hash, key, value, null);
641
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
642
treeifyBin(tab, hash);
643
break;
644
}
645
if (e.hash == hash &&
646
((k = e.key) == key || (key != null && key.equals(k))))
647
break;
648
p = e;
649
}
650
}
651
if (e != null) { // existing mapping for key
652
V oldValue = e.value;
653
if (!onlyIfAbsent || oldValue == null)
654
e.value = value;
655
afterNodeAccess(e);
656
return oldValue;
657
}
658
}
659
++modCount;
660
if (++size > threshold)
661
resize();
662
afterNodeInsertion(evict);
663
return null;
664
}
665
666
/**
667
* Initializes or doubles table size. If null, allocates in
668
* accord with initial capacity target held in field threshold.
669
* Otherwise, because we are using power-of-two expansion, the
670
* elements from each bin must either stay at same index, or move
671
* with a power of two offset in the new table.
672
*
673
* @return the table
674
*/
675
final Node<K,V>[] resize() {
676
Node<K,V>[] oldTab = table;
677
int oldCap = (oldTab == null) ? 0 : oldTab.length;
678
int oldThr = threshold;
679
int newCap, newThr = 0;
680
if (oldCap > 0) {
681
if (oldCap >= MAXIMUM_CAPACITY) {
682
threshold = Integer.MAX_VALUE;
683
return oldTab;
684
}
685
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
686
oldCap >= DEFAULT_INITIAL_CAPACITY)
687
newThr = oldThr << 1; // double threshold
688
}
689
else if (oldThr > 0) // initial capacity was placed in threshold
690
newCap = oldThr;
691
else { // zero initial threshold signifies using defaults
692
newCap = DEFAULT_INITIAL_CAPACITY;
693
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
694
}
695
if (newThr == 0) {
696
float ft = (float)newCap * loadFactor;
697
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
698
(int)ft : Integer.MAX_VALUE);
699
}
700
threshold = newThr;
701
@SuppressWarnings({"rawtypes","unchecked"})
702
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
703
table = newTab;
704
if (oldTab != null) {
705
for (int j = 0; j < oldCap; ++j) {
706
Node<K,V> e;
707
if ((e = oldTab[j]) != null) {
708
oldTab[j] = null;
709
if (e.next == null)
710
newTab[e.hash & (newCap - 1)] = e;
711
else if (e instanceof TreeNode)
712
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
713
else { // preserve order
714
Node<K,V> loHead = null, loTail = null;
715
Node<K,V> hiHead = null, hiTail = null;
716
Node<K,V> next;
717
do {
718
next = e.next;
719
if ((e.hash & oldCap) == 0) {
720
if (loTail == null)
721
loHead = e;
722
else
723
loTail.next = e;
724
loTail = e;
725
}
726
else {
727
if (hiTail == null)
728
hiHead = e;
729
else
730
hiTail.next = e;
731
hiTail = e;
732
}
733
} while ((e = next) != null);
734
if (loTail != null) {
735
loTail.next = null;
736
newTab[j] = loHead;
737
}
738
if (hiTail != null) {
739
hiTail.next = null;
740
newTab[j + oldCap] = hiHead;
741
}
742
}
743
}
744
}
745
}
746
return newTab;
747
}
748
749
/**
750
* Replaces all linked nodes in bin at index for given hash unless
751
* table is too small, in which case resizes instead.
752
*/
753
final void treeifyBin(Node<K,V>[] tab, int hash) {
754
int n, index; Node<K,V> e;
755
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
756
resize();
757
else if ((e = tab[index = (n - 1) & hash]) != null) {
758
TreeNode<K,V> hd = null, tl = null;
759
do {
760
TreeNode<K,V> p = replacementTreeNode(e, null);
761
if (tl == null)
762
hd = p;
763
else {
764
p.prev = tl;
765
tl.next = p;
766
}
767
tl = p;
768
} while ((e = e.next) != null);
769
if ((tab[index] = hd) != null)
770
hd.treeify(tab);
771
}
772
}
773
774
/**
775
* Copies all of the mappings from the specified map to this map.
776
* These mappings will replace any mappings that this map had for
777
* any of the keys currently in the specified map.
778
*
779
* @param m mappings to be stored in this map
780
* @throws NullPointerException if the specified map is null
781
*/
782
public void putAll(Map<? extends K, ? extends V> m) {
783
putMapEntries(m, true);
784
}
785
786
/**
787
* Removes the mapping for the specified key from this map if present.
788
*
789
* @param key key whose mapping is to be removed from the map
790
* @return the previous value associated with {@code key}, or
791
* {@code null} if there was no mapping for {@code key}.
792
* (A {@code null} return can also indicate that the map
793
* previously associated {@code null} with {@code key}.)
794
*/
795
public V remove(Object key) {
796
Node<K,V> e;
797
return (e = removeNode(hash(key), key, null, false, true)) == null ?
798
null : e.value;
799
}
800
801
/**
802
* Implements Map.remove and related methods.
803
*
804
* @param hash hash for key
805
* @param key the key
806
* @param value the value to match if matchValue, else ignored
807
* @param matchValue if true only remove if value is equal
808
* @param movable if false do not move other nodes while removing
809
* @return the node, or null if none
810
*/
811
final Node<K,V> removeNode(int hash, Object key, Object value,
812
boolean matchValue, boolean movable) {
813
Node<K,V>[] tab; Node<K,V> p; int n, index;
814
if ((tab = table) != null && (n = tab.length) > 0 &&
815
(p = tab[index = (n - 1) & hash]) != null) {
816
Node<K,V> node = null, e; K k; V v;
817
if (p.hash == hash &&
818
((k = p.key) == key || (key != null && key.equals(k))))
819
node = p;
820
else if ((e = p.next) != null) {
821
if (p instanceof TreeNode)
822
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
823
else {
824
do {
825
if (e.hash == hash &&
826
((k = e.key) == key ||
827
(key != null && key.equals(k)))) {
828
node = e;
829
break;
830
}
831
p = e;
832
} while ((e = e.next) != null);
833
}
834
}
835
if (node != null && (!matchValue || (v = node.value) == value ||
836
(value != null && value.equals(v)))) {
837
if (node instanceof TreeNode)
838
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
839
else if (node == p)
840
tab[index] = node.next;
841
else
842
p.next = node.next;
843
++modCount;
844
--size;
845
afterNodeRemoval(node);
846
return node;
847
}
848
}
849
return null;
850
}
851
852
/**
853
* Removes all of the mappings from this map.
854
* The map will be empty after this call returns.
855
*/
856
public void clear() {
857
Node<K,V>[] tab;
858
modCount++;
859
if ((tab = table) != null && size > 0) {
860
size = 0;
861
for (int i = 0; i < tab.length; ++i)
862
tab[i] = null;
863
}
864
}
865
866
/**
867
* Returns {@code true} if this map maps one or more keys to the
868
* specified value.
869
*
870
* @param value value whose presence in this map is to be tested
871
* @return {@code true} if this map maps one or more keys to the
872
* specified value
873
*/
874
public boolean containsValue(Object value) {
875
Node<K,V>[] tab; V v;
876
if ((tab = table) != null && size > 0) {
877
for (Node<K,V> e : tab) {
878
for (; e != null; e = e.next) {
879
if ((v = e.value) == value ||
880
(value != null && value.equals(v)))
881
return true;
882
}
883
}
884
}
885
return false;
886
}
887
888
/**
889
* Returns a {@link Set} view of the keys contained in this map.
890
* The set is backed by the map, so changes to the map are
891
* reflected in the set, and vice-versa. If the map is modified
892
* while an iteration over the set is in progress (except through
893
* the iterator's own {@code remove} operation), the results of
894
* the iteration are undefined. The set supports element removal,
895
* which removes the corresponding mapping from the map, via the
896
* {@code Iterator.remove}, {@code Set.remove},
897
* {@code removeAll}, {@code retainAll}, and {@code clear}
898
* operations. It does not support the {@code add} or {@code addAll}
899
* operations.
900
*
901
* @return a set view of the keys contained in this map
902
*/
903
public Set<K> keySet() {
904
Set<K> ks = keySet;
905
if (ks == null) {
906
ks = new KeySet();
907
keySet = ks;
908
}
909
return ks;
910
}
911
912
/**
913
* Prepares the array for {@link Collection#toArray(Object[])} implementation.
914
* If supplied array is smaller than this map size, a new array is allocated.
915
* If supplied array is bigger than this map size, a null is written at size index.
916
*
917
* @param a an original array passed to {@code toArray()} method
918
* @param <T> type of array elements
919
* @return an array ready to be filled and returned from {@code toArray()} method.
920
*/
921
@SuppressWarnings("unchecked")
922
final <T> T[] prepareArray(T[] a) {
923
int size = this.size;
924
if (a.length < size) {
925
return (T[]) java.lang.reflect.Array
926
.newInstance(a.getClass().getComponentType(), size);
927
}
928
if (a.length > size) {
929
a[size] = null;
930
}
931
return a;
932
}
933
934
/**
935
* Fills an array with this map keys and returns it. This method assumes
936
* that input array is big enough to fit all the keys. Use
937
* {@link #prepareArray(Object[])} to ensure this.
938
*
939
* @param a an array to fill
940
* @param <T> type of array elements
941
* @return supplied array
942
*/
943
<T> T[] keysToArray(T[] a) {
944
Object[] r = a;
945
Node<K,V>[] tab;
946
int idx = 0;
947
if (size > 0 && (tab = table) != null) {
948
for (Node<K,V> e : tab) {
949
for (; e != null; e = e.next) {
950
r[idx++] = e.key;
951
}
952
}
953
}
954
return a;
955
}
956
957
/**
958
* Fills an array with this map values and returns it. This method assumes
959
* that input array is big enough to fit all the values. Use
960
* {@link #prepareArray(Object[])} to ensure this.
961
*
962
* @param a an array to fill
963
* @param <T> type of array elements
964
* @return supplied array
965
*/
966
<T> T[] valuesToArray(T[] a) {
967
Object[] r = a;
968
Node<K,V>[] tab;
969
int idx = 0;
970
if (size > 0 && (tab = table) != null) {
971
for (Node<K,V> e : tab) {
972
for (; e != null; e = e.next) {
973
r[idx++] = e.value;
974
}
975
}
976
}
977
return a;
978
}
979
980
final class KeySet extends AbstractSet<K> {
981
public final int size() { return size; }
982
public final void clear() { HashMap.this.clear(); }
983
public final Iterator<K> iterator() { return new KeyIterator(); }
984
public final boolean contains(Object o) { return containsKey(o); }
985
public final boolean remove(Object key) {
986
return removeNode(hash(key), key, null, false, true) != null;
987
}
988
public final Spliterator<K> spliterator() {
989
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
990
}
991
992
public Object[] toArray() {
993
return keysToArray(new Object[size]);
994
}
995
996
public <T> T[] toArray(T[] a) {
997
return keysToArray(prepareArray(a));
998
}
999
1000
public final void forEach(Consumer<? super K> action) {
1001
Node<K,V>[] tab;
1002
if (action == null)
1003
throw new NullPointerException();
1004
if (size > 0 && (tab = table) != null) {
1005
int mc = modCount;
1006
for (Node<K,V> e : tab) {
1007
for (; e != null; e = e.next)
1008
action.accept(e.key);
1009
}
1010
if (modCount != mc)
1011
throw new ConcurrentModificationException();
1012
}
1013
}
1014
}
1015
1016
/**
1017
* Returns a {@link Collection} view of the values contained in this map.
1018
* The collection is backed by the map, so changes to the map are
1019
* reflected in the collection, and vice-versa. If the map is
1020
* modified while an iteration over the collection is in progress
1021
* (except through the iterator's own {@code remove} operation),
1022
* the results of the iteration are undefined. The collection
1023
* supports element removal, which removes the corresponding
1024
* mapping from the map, via the {@code Iterator.remove},
1025
* {@code Collection.remove}, {@code removeAll},
1026
* {@code retainAll} and {@code clear} operations. It does not
1027
* support the {@code add} or {@code addAll} operations.
1028
*
1029
* @return a view of the values contained in this map
1030
*/
1031
public Collection<V> values() {
1032
Collection<V> vs = values;
1033
if (vs == null) {
1034
vs = new Values();
1035
values = vs;
1036
}
1037
return vs;
1038
}
1039
1040
final class Values extends AbstractCollection<V> {
1041
public final int size() { return size; }
1042
public final void clear() { HashMap.this.clear(); }
1043
public final Iterator<V> iterator() { return new ValueIterator(); }
1044
public final boolean contains(Object o) { return containsValue(o); }
1045
public final Spliterator<V> spliterator() {
1046
return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
1047
}
1048
1049
public Object[] toArray() {
1050
return valuesToArray(new Object[size]);
1051
}
1052
1053
public <T> T[] toArray(T[] a) {
1054
return valuesToArray(prepareArray(a));
1055
}
1056
1057
public final void forEach(Consumer<? super V> action) {
1058
Node<K,V>[] tab;
1059
if (action == null)
1060
throw new NullPointerException();
1061
if (size > 0 && (tab = table) != null) {
1062
int mc = modCount;
1063
for (Node<K,V> e : tab) {
1064
for (; e != null; e = e.next)
1065
action.accept(e.value);
1066
}
1067
if (modCount != mc)
1068
throw new ConcurrentModificationException();
1069
}
1070
}
1071
}
1072
1073
/**
1074
* Returns a {@link Set} view of the mappings contained in this map.
1075
* The set is backed by the map, so changes to the map are
1076
* reflected in the set, and vice-versa. If the map is modified
1077
* while an iteration over the set is in progress (except through
1078
* the iterator's own {@code remove} operation, or through the
1079
* {@code setValue} operation on a map entry returned by the
1080
* iterator) the results of the iteration are undefined. The set
1081
* supports element removal, which removes the corresponding
1082
* mapping from the map, via the {@code Iterator.remove},
1083
* {@code Set.remove}, {@code removeAll}, {@code retainAll} and
1084
* {@code clear} operations. It does not support the
1085
* {@code add} or {@code addAll} operations.
1086
*
1087
* @return a set view of the mappings contained in this map
1088
*/
1089
public Set<Map.Entry<K,V>> entrySet() {
1090
Set<Map.Entry<K,V>> es;
1091
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
1092
}
1093
1094
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1095
public final int size() { return size; }
1096
public final void clear() { HashMap.this.clear(); }
1097
public final Iterator<Map.Entry<K,V>> iterator() {
1098
return new EntryIterator();
1099
}
1100
public final boolean contains(Object o) {
1101
if (!(o instanceof Map.Entry<?, ?> e))
1102
return false;
1103
Object key = e.getKey();
1104
Node<K,V> candidate = getNode(key);
1105
return candidate != null && candidate.equals(e);
1106
}
1107
public final boolean remove(Object o) {
1108
if (o instanceof Map.Entry<?, ?> e) {
1109
Object key = e.getKey();
1110
Object value = e.getValue();
1111
return removeNode(hash(key), key, value, true, true) != null;
1112
}
1113
return false;
1114
}
1115
public final Spliterator<Map.Entry<K,V>> spliterator() {
1116
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
1117
}
1118
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
1119
Node<K,V>[] tab;
1120
if (action == null)
1121
throw new NullPointerException();
1122
if (size > 0 && (tab = table) != null) {
1123
int mc = modCount;
1124
for (Node<K,V> e : tab) {
1125
for (; e != null; e = e.next)
1126
action.accept(e);
1127
}
1128
if (modCount != mc)
1129
throw new ConcurrentModificationException();
1130
}
1131
}
1132
}
1133
1134
// Overrides of JDK8 Map extension methods
1135
1136
@Override
1137
public V getOrDefault(Object key, V defaultValue) {
1138
Node<K,V> e;
1139
return (e = getNode(key)) == null ? defaultValue : e.value;
1140
}
1141
1142
@Override
1143
public V putIfAbsent(K key, V value) {
1144
return putVal(hash(key), key, value, true, true);
1145
}
1146
1147
@Override
1148
public boolean remove(Object key, Object value) {
1149
return removeNode(hash(key), key, value, true, true) != null;
1150
}
1151
1152
@Override
1153
public boolean replace(K key, V oldValue, V newValue) {
1154
Node<K,V> e; V v;
1155
if ((e = getNode(key)) != null &&
1156
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
1157
e.value = newValue;
1158
afterNodeAccess(e);
1159
return true;
1160
}
1161
return false;
1162
}
1163
1164
@Override
1165
public V replace(K key, V value) {
1166
Node<K,V> e;
1167
if ((e = getNode(key)) != null) {
1168
V oldValue = e.value;
1169
e.value = value;
1170
afterNodeAccess(e);
1171
return oldValue;
1172
}
1173
return null;
1174
}
1175
1176
/**
1177
* {@inheritDoc}
1178
*
1179
* <p>This method will, on a best-effort basis, throw a
1180
* {@link ConcurrentModificationException} if it is detected that the
1181
* mapping function modifies this map during computation.
1182
*
1183
* @throws ConcurrentModificationException if it is detected that the
1184
* mapping function modified this map
1185
*/
1186
@Override
1187
public V computeIfAbsent(K key,
1188
Function<? super K, ? extends V> mappingFunction) {
1189
if (mappingFunction == null)
1190
throw new NullPointerException();
1191
int hash = hash(key);
1192
Node<K,V>[] tab; Node<K,V> first; int n, i;
1193
int binCount = 0;
1194
TreeNode<K,V> t = null;
1195
Node<K,V> old = null;
1196
if (size > threshold || (tab = table) == null ||
1197
(n = tab.length) == 0)
1198
n = (tab = resize()).length;
1199
if ((first = tab[i = (n - 1) & hash]) != null) {
1200
if (first instanceof TreeNode)
1201
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
1202
else {
1203
Node<K,V> e = first; K k;
1204
do {
1205
if (e.hash == hash &&
1206
((k = e.key) == key || (key != null && key.equals(k)))) {
1207
old = e;
1208
break;
1209
}
1210
++binCount;
1211
} while ((e = e.next) != null);
1212
}
1213
V oldValue;
1214
if (old != null && (oldValue = old.value) != null) {
1215
afterNodeAccess(old);
1216
return oldValue;
1217
}
1218
}
1219
int mc = modCount;
1220
V v = mappingFunction.apply(key);
1221
if (mc != modCount) { throw new ConcurrentModificationException(); }
1222
if (v == null) {
1223
return null;
1224
} else if (old != null) {
1225
old.value = v;
1226
afterNodeAccess(old);
1227
return v;
1228
}
1229
else if (t != null)
1230
t.putTreeVal(this, tab, hash, key, v);
1231
else {
1232
tab[i] = newNode(hash, key, v, first);
1233
if (binCount >= TREEIFY_THRESHOLD - 1)
1234
treeifyBin(tab, hash);
1235
}
1236
modCount = mc + 1;
1237
++size;
1238
afterNodeInsertion(true);
1239
return v;
1240
}
1241
1242
/**
1243
* {@inheritDoc}
1244
*
1245
* <p>This method will, on a best-effort basis, throw a
1246
* {@link ConcurrentModificationException} if it is detected that the
1247
* remapping function modifies this map during computation.
1248
*
1249
* @throws ConcurrentModificationException if it is detected that the
1250
* remapping function modified this map
1251
*/
1252
@Override
1253
public V computeIfPresent(K key,
1254
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1255
if (remappingFunction == null)
1256
throw new NullPointerException();
1257
Node<K,V> e; V oldValue;
1258
if ((e = getNode(key)) != null &&
1259
(oldValue = e.value) != null) {
1260
int mc = modCount;
1261
V v = remappingFunction.apply(key, oldValue);
1262
if (mc != modCount) { throw new ConcurrentModificationException(); }
1263
if (v != null) {
1264
e.value = v;
1265
afterNodeAccess(e);
1266
return v;
1267
}
1268
else {
1269
int hash = hash(key);
1270
removeNode(hash, key, null, false, true);
1271
}
1272
}
1273
return null;
1274
}
1275
1276
/**
1277
* {@inheritDoc}
1278
*
1279
* <p>This method will, on a best-effort basis, throw a
1280
* {@link ConcurrentModificationException} if it is detected that the
1281
* remapping function modifies this map during computation.
1282
*
1283
* @throws ConcurrentModificationException if it is detected that the
1284
* remapping function modified this map
1285
*/
1286
@Override
1287
public V compute(K key,
1288
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1289
if (remappingFunction == null)
1290
throw new NullPointerException();
1291
int hash = hash(key);
1292
Node<K,V>[] tab; Node<K,V> first; int n, i;
1293
int binCount = 0;
1294
TreeNode<K,V> t = null;
1295
Node<K,V> old = null;
1296
if (size > threshold || (tab = table) == null ||
1297
(n = tab.length) == 0)
1298
n = (tab = resize()).length;
1299
if ((first = tab[i = (n - 1) & hash]) != null) {
1300
if (first instanceof TreeNode)
1301
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
1302
else {
1303
Node<K,V> e = first; K k;
1304
do {
1305
if (e.hash == hash &&
1306
((k = e.key) == key || (key != null && key.equals(k)))) {
1307
old = e;
1308
break;
1309
}
1310
++binCount;
1311
} while ((e = e.next) != null);
1312
}
1313
}
1314
V oldValue = (old == null) ? null : old.value;
1315
int mc = modCount;
1316
V v = remappingFunction.apply(key, oldValue);
1317
if (mc != modCount) { throw new ConcurrentModificationException(); }
1318
if (old != null) {
1319
if (v != null) {
1320
old.value = v;
1321
afterNodeAccess(old);
1322
}
1323
else
1324
removeNode(hash, key, null, false, true);
1325
}
1326
else if (v != null) {
1327
if (t != null)
1328
t.putTreeVal(this, tab, hash, key, v);
1329
else {
1330
tab[i] = newNode(hash, key, v, first);
1331
if (binCount >= TREEIFY_THRESHOLD - 1)
1332
treeifyBin(tab, hash);
1333
}
1334
modCount = mc + 1;
1335
++size;
1336
afterNodeInsertion(true);
1337
}
1338
return v;
1339
}
1340
1341
/**
1342
* {@inheritDoc}
1343
*
1344
* <p>This method will, on a best-effort basis, throw a
1345
* {@link ConcurrentModificationException} if it is detected that the
1346
* remapping function modifies this map during computation.
1347
*
1348
* @throws ConcurrentModificationException if it is detected that the
1349
* remapping function modified this map
1350
*/
1351
@Override
1352
public V merge(K key, V value,
1353
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1354
if (value == null || remappingFunction == null)
1355
throw new NullPointerException();
1356
int hash = hash(key);
1357
Node<K,V>[] tab; Node<K,V> first; int n, i;
1358
int binCount = 0;
1359
TreeNode<K,V> t = null;
1360
Node<K,V> old = null;
1361
if (size > threshold || (tab = table) == null ||
1362
(n = tab.length) == 0)
1363
n = (tab = resize()).length;
1364
if ((first = tab[i = (n - 1) & hash]) != null) {
1365
if (first instanceof TreeNode)
1366
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
1367
else {
1368
Node<K,V> e = first; K k;
1369
do {
1370
if (e.hash == hash &&
1371
((k = e.key) == key || (key != null && key.equals(k)))) {
1372
old = e;
1373
break;
1374
}
1375
++binCount;
1376
} while ((e = e.next) != null);
1377
}
1378
}
1379
if (old != null) {
1380
V v;
1381
if (old.value != null) {
1382
int mc = modCount;
1383
v = remappingFunction.apply(old.value, value);
1384
if (mc != modCount) {
1385
throw new ConcurrentModificationException();
1386
}
1387
} else {
1388
v = value;
1389
}
1390
if (v != null) {
1391
old.value = v;
1392
afterNodeAccess(old);
1393
}
1394
else
1395
removeNode(hash, key, null, false, true);
1396
return v;
1397
} else {
1398
if (t != null)
1399
t.putTreeVal(this, tab, hash, key, value);
1400
else {
1401
tab[i] = newNode(hash, key, value, first);
1402
if (binCount >= TREEIFY_THRESHOLD - 1)
1403
treeifyBin(tab, hash);
1404
}
1405
++modCount;
1406
++size;
1407
afterNodeInsertion(true);
1408
return value;
1409
}
1410
}
1411
1412
@Override
1413
public void forEach(BiConsumer<? super K, ? super V> action) {
1414
Node<K,V>[] tab;
1415
if (action == null)
1416
throw new NullPointerException();
1417
if (size > 0 && (tab = table) != null) {
1418
int mc = modCount;
1419
for (Node<K,V> e : tab) {
1420
for (; e != null; e = e.next)
1421
action.accept(e.key, e.value);
1422
}
1423
if (modCount != mc)
1424
throw new ConcurrentModificationException();
1425
}
1426
}
1427
1428
@Override
1429
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1430
Node<K,V>[] tab;
1431
if (function == null)
1432
throw new NullPointerException();
1433
if (size > 0 && (tab = table) != null) {
1434
int mc = modCount;
1435
for (Node<K,V> e : tab) {
1436
for (; e != null; e = e.next) {
1437
e.value = function.apply(e.key, e.value);
1438
}
1439
}
1440
if (modCount != mc)
1441
throw new ConcurrentModificationException();
1442
}
1443
}
1444
1445
/* ------------------------------------------------------------ */
1446
// Cloning and serialization
1447
1448
/**
1449
* Returns a shallow copy of this {@code HashMap} instance: the keys and
1450
* values themselves are not cloned.
1451
*
1452
* @return a shallow copy of this map
1453
*/
1454
@SuppressWarnings("unchecked")
1455
@Override
1456
public Object clone() {
1457
HashMap<K,V> result;
1458
try {
1459
result = (HashMap<K,V>)super.clone();
1460
} catch (CloneNotSupportedException e) {
1461
// this shouldn't happen, since we are Cloneable
1462
throw new InternalError(e);
1463
}
1464
result.reinitialize();
1465
result.putMapEntries(this, false);
1466
return result;
1467
}
1468
1469
// These methods are also used when serializing HashSets
1470
final float loadFactor() { return loadFactor; }
1471
final int capacity() {
1472
return (table != null) ? table.length :
1473
(threshold > 0) ? threshold :
1474
DEFAULT_INITIAL_CAPACITY;
1475
}
1476
1477
/**
1478
* Saves this map to a stream (that is, serializes it).
1479
*
1480
* @param s the stream
1481
* @throws IOException if an I/O error occurs
1482
* @serialData The <i>capacity</i> of the HashMap (the length of the
1483
* bucket array) is emitted (int), followed by the
1484
* <i>size</i> (an int, the number of key-value
1485
* mappings), followed by the key (Object) and value (Object)
1486
* for each key-value mapping. The key-value mappings are
1487
* emitted in no particular order.
1488
*/
1489
@java.io.Serial
1490
private void writeObject(java.io.ObjectOutputStream s)
1491
throws IOException {
1492
int buckets = capacity();
1493
// Write out the threshold, loadfactor, and any hidden stuff
1494
s.defaultWriteObject();
1495
s.writeInt(buckets);
1496
s.writeInt(size);
1497
internalWriteEntries(s);
1498
}
1499
1500
/**
1501
* Reconstitutes this map from a stream (that is, deserializes it).
1502
* @param s the stream
1503
* @throws ClassNotFoundException if the class of a serialized object
1504
* could not be found
1505
* @throws IOException if an I/O error occurs
1506
*/
1507
@java.io.Serial
1508
private void readObject(ObjectInputStream s)
1509
throws IOException, ClassNotFoundException {
1510
1511
ObjectInputStream.GetField fields = s.readFields();
1512
1513
// Read loadFactor (ignore threshold)
1514
float lf = fields.get("loadFactor", 0.75f);
1515
if (lf <= 0 || Float.isNaN(lf))
1516
throw new InvalidObjectException("Illegal load factor: " + lf);
1517
1518
lf = Math.min(Math.max(0.25f, lf), 4.0f);
1519
HashMap.UnsafeHolder.putLoadFactor(this, lf);
1520
1521
reinitialize();
1522
1523
s.readInt(); // Read and ignore number of buckets
1524
int mappings = s.readInt(); // Read number of mappings (size)
1525
if (mappings < 0) {
1526
throw new InvalidObjectException("Illegal mappings count: " + mappings);
1527
} else if (mappings == 0) {
1528
// use defaults
1529
} else if (mappings > 0) {
1530
float fc = (float)mappings / lf + 1.0f;
1531
int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
1532
DEFAULT_INITIAL_CAPACITY :
1533
(fc >= MAXIMUM_CAPACITY) ?
1534
MAXIMUM_CAPACITY :
1535
tableSizeFor((int)fc));
1536
float ft = (float)cap * lf;
1537
threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
1538
(int)ft : Integer.MAX_VALUE);
1539
1540
// Check Map.Entry[].class since it's the nearest public type to
1541
// what we're actually creating.
1542
SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Map.Entry[].class, cap);
1543
@SuppressWarnings({"rawtypes","unchecked"})
1544
Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
1545
table = tab;
1546
1547
// Read the keys and values, and put the mappings in the HashMap
1548
for (int i = 0; i < mappings; i++) {
1549
@SuppressWarnings("unchecked")
1550
K key = (K) s.readObject();
1551
@SuppressWarnings("unchecked")
1552
V value = (V) s.readObject();
1553
putVal(hash(key), key, value, false, false);
1554
}
1555
}
1556
}
1557
1558
// Support for resetting final field during deserializing
1559
private static final class UnsafeHolder {
1560
private UnsafeHolder() { throw new InternalError(); }
1561
private static final jdk.internal.misc.Unsafe unsafe
1562
= jdk.internal.misc.Unsafe.getUnsafe();
1563
private static final long LF_OFFSET
1564
= unsafe.objectFieldOffset(HashMap.class, "loadFactor");
1565
static void putLoadFactor(HashMap<?, ?> map, float lf) {
1566
unsafe.putFloat(map, LF_OFFSET, lf);
1567
}
1568
}
1569
1570
/* ------------------------------------------------------------ */
1571
// iterators
1572
1573
abstract class HashIterator {
1574
Node<K,V> next; // next entry to return
1575
Node<K,V> current; // current entry
1576
int expectedModCount; // for fast-fail
1577
int index; // current slot
1578
1579
HashIterator() {
1580
expectedModCount = modCount;
1581
Node<K,V>[] t = table;
1582
current = next = null;
1583
index = 0;
1584
if (t != null && size > 0) { // advance to first entry
1585
do {} while (index < t.length && (next = t[index++]) == null);
1586
}
1587
}
1588
1589
public final boolean hasNext() {
1590
return next != null;
1591
}
1592
1593
final Node<K,V> nextNode() {
1594
Node<K,V>[] t;
1595
Node<K,V> e = next;
1596
if (modCount != expectedModCount)
1597
throw new ConcurrentModificationException();
1598
if (e == null)
1599
throw new NoSuchElementException();
1600
if ((next = (current = e).next) == null && (t = table) != null) {
1601
do {} while (index < t.length && (next = t[index++]) == null);
1602
}
1603
return e;
1604
}
1605
1606
public final void remove() {
1607
Node<K,V> p = current;
1608
if (p == null)
1609
throw new IllegalStateException();
1610
if (modCount != expectedModCount)
1611
throw new ConcurrentModificationException();
1612
current = null;
1613
removeNode(p.hash, p.key, null, false, false);
1614
expectedModCount = modCount;
1615
}
1616
}
1617
1618
final class KeyIterator extends HashIterator
1619
implements Iterator<K> {
1620
public final K next() { return nextNode().key; }
1621
}
1622
1623
final class ValueIterator extends HashIterator
1624
implements Iterator<V> {
1625
public final V next() { return nextNode().value; }
1626
}
1627
1628
final class EntryIterator extends HashIterator
1629
implements Iterator<Map.Entry<K,V>> {
1630
public final Map.Entry<K,V> next() { return nextNode(); }
1631
}
1632
1633
/* ------------------------------------------------------------ */
1634
// spliterators
1635
1636
static class HashMapSpliterator<K,V> {
1637
final HashMap<K,V> map;
1638
Node<K,V> current; // current node
1639
int index; // current index, modified on advance/split
1640
int fence; // one past last index
1641
int est; // size estimate
1642
int expectedModCount; // for comodification checks
1643
1644
HashMapSpliterator(HashMap<K,V> m, int origin,
1645
int fence, int est,
1646
int expectedModCount) {
1647
this.map = m;
1648
this.index = origin;
1649
this.fence = fence;
1650
this.est = est;
1651
this.expectedModCount = expectedModCount;
1652
}
1653
1654
final int getFence() { // initialize fence and size on first use
1655
int hi;
1656
if ((hi = fence) < 0) {
1657
HashMap<K,V> m = map;
1658
est = m.size;
1659
expectedModCount = m.modCount;
1660
Node<K,V>[] tab = m.table;
1661
hi = fence = (tab == null) ? 0 : tab.length;
1662
}
1663
return hi;
1664
}
1665
1666
public final long estimateSize() {
1667
getFence(); // force init
1668
return (long) est;
1669
}
1670
}
1671
1672
static final class KeySpliterator<K,V>
1673
extends HashMapSpliterator<K,V>
1674
implements Spliterator<K> {
1675
KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,
1676
int expectedModCount) {
1677
super(m, origin, fence, est, expectedModCount);
1678
}
1679
1680
public KeySpliterator<K,V> trySplit() {
1681
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1682
return (lo >= mid || current != null) ? null :
1683
new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
1684
expectedModCount);
1685
}
1686
1687
public void forEachRemaining(Consumer<? super K> action) {
1688
int i, hi, mc;
1689
if (action == null)
1690
throw new NullPointerException();
1691
HashMap<K,V> m = map;
1692
Node<K,V>[] tab = m.table;
1693
if ((hi = fence) < 0) {
1694
mc = expectedModCount = m.modCount;
1695
hi = fence = (tab == null) ? 0 : tab.length;
1696
}
1697
else
1698
mc = expectedModCount;
1699
if (tab != null && tab.length >= hi &&
1700
(i = index) >= 0 && (i < (index = hi) || current != null)) {
1701
Node<K,V> p = current;
1702
current = null;
1703
do {
1704
if (p == null)
1705
p = tab[i++];
1706
else {
1707
action.accept(p.key);
1708
p = p.next;
1709
}
1710
} while (p != null || i < hi);
1711
if (m.modCount != mc)
1712
throw new ConcurrentModificationException();
1713
}
1714
}
1715
1716
public boolean tryAdvance(Consumer<? super K> action) {
1717
int hi;
1718
if (action == null)
1719
throw new NullPointerException();
1720
Node<K,V>[] tab = map.table;
1721
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
1722
while (current != null || index < hi) {
1723
if (current == null)
1724
current = tab[index++];
1725
else {
1726
K k = current.key;
1727
current = current.next;
1728
action.accept(k);
1729
if (map.modCount != expectedModCount)
1730
throw new ConcurrentModificationException();
1731
return true;
1732
}
1733
}
1734
}
1735
return false;
1736
}
1737
1738
public int characteristics() {
1739
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
1740
Spliterator.DISTINCT;
1741
}
1742
}
1743
1744
static final class ValueSpliterator<K,V>
1745
extends HashMapSpliterator<K,V>
1746
implements Spliterator<V> {
1747
ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,
1748
int expectedModCount) {
1749
super(m, origin, fence, est, expectedModCount);
1750
}
1751
1752
public ValueSpliterator<K,V> trySplit() {
1753
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1754
return (lo >= mid || current != null) ? null :
1755
new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
1756
expectedModCount);
1757
}
1758
1759
public void forEachRemaining(Consumer<? super V> action) {
1760
int i, hi, mc;
1761
if (action == null)
1762
throw new NullPointerException();
1763
HashMap<K,V> m = map;
1764
Node<K,V>[] tab = m.table;
1765
if ((hi = fence) < 0) {
1766
mc = expectedModCount = m.modCount;
1767
hi = fence = (tab == null) ? 0 : tab.length;
1768
}
1769
else
1770
mc = expectedModCount;
1771
if (tab != null && tab.length >= hi &&
1772
(i = index) >= 0 && (i < (index = hi) || current != null)) {
1773
Node<K,V> p = current;
1774
current = null;
1775
do {
1776
if (p == null)
1777
p = tab[i++];
1778
else {
1779
action.accept(p.value);
1780
p = p.next;
1781
}
1782
} while (p != null || i < hi);
1783
if (m.modCount != mc)
1784
throw new ConcurrentModificationException();
1785
}
1786
}
1787
1788
public boolean tryAdvance(Consumer<? super V> action) {
1789
int hi;
1790
if (action == null)
1791
throw new NullPointerException();
1792
Node<K,V>[] tab = map.table;
1793
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
1794
while (current != null || index < hi) {
1795
if (current == null)
1796
current = tab[index++];
1797
else {
1798
V v = current.value;
1799
current = current.next;
1800
action.accept(v);
1801
if (map.modCount != expectedModCount)
1802
throw new ConcurrentModificationException();
1803
return true;
1804
}
1805
}
1806
}
1807
return false;
1808
}
1809
1810
public int characteristics() {
1811
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
1812
}
1813
}
1814
1815
static final class EntrySpliterator<K,V>
1816
extends HashMapSpliterator<K,V>
1817
implements Spliterator<Map.Entry<K,V>> {
1818
EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,
1819
int expectedModCount) {
1820
super(m, origin, fence, est, expectedModCount);
1821
}
1822
1823
public EntrySpliterator<K,V> trySplit() {
1824
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1825
return (lo >= mid || current != null) ? null :
1826
new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
1827
expectedModCount);
1828
}
1829
1830
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
1831
int i, hi, mc;
1832
if (action == null)
1833
throw new NullPointerException();
1834
HashMap<K,V> m = map;
1835
Node<K,V>[] tab = m.table;
1836
if ((hi = fence) < 0) {
1837
mc = expectedModCount = m.modCount;
1838
hi = fence = (tab == null) ? 0 : tab.length;
1839
}
1840
else
1841
mc = expectedModCount;
1842
if (tab != null && tab.length >= hi &&
1843
(i = index) >= 0 && (i < (index = hi) || current != null)) {
1844
Node<K,V> p = current;
1845
current = null;
1846
do {
1847
if (p == null)
1848
p = tab[i++];
1849
else {
1850
action.accept(p);
1851
p = p.next;
1852
}
1853
} while (p != null || i < hi);
1854
if (m.modCount != mc)
1855
throw new ConcurrentModificationException();
1856
}
1857
}
1858
1859
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
1860
int hi;
1861
if (action == null)
1862
throw new NullPointerException();
1863
Node<K,V>[] tab = map.table;
1864
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
1865
while (current != null || index < hi) {
1866
if (current == null)
1867
current = tab[index++];
1868
else {
1869
Node<K,V> e = current;
1870
current = current.next;
1871
action.accept(e);
1872
if (map.modCount != expectedModCount)
1873
throw new ConcurrentModificationException();
1874
return true;
1875
}
1876
}
1877
}
1878
return false;
1879
}
1880
1881
public int characteristics() {
1882
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
1883
Spliterator.DISTINCT;
1884
}
1885
}
1886
1887
/* ------------------------------------------------------------ */
1888
// LinkedHashMap support
1889
1890
1891
/*
1892
* The following package-protected methods are designed to be
1893
* overridden by LinkedHashMap, but not by any other subclass.
1894
* Nearly all other internal methods are also package-protected
1895
* but are declared final, so can be used by LinkedHashMap, view
1896
* classes, and HashSet.
1897
*/
1898
1899
// Create a regular (non-tree) node
1900
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
1901
return new Node<>(hash, key, value, next);
1902
}
1903
1904
// For conversion from TreeNodes to plain nodes
1905
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
1906
return new Node<>(p.hash, p.key, p.value, next);
1907
}
1908
1909
// Create a tree bin node
1910
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
1911
return new TreeNode<>(hash, key, value, next);
1912
}
1913
1914
// For treeifyBin
1915
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
1916
return new TreeNode<>(p.hash, p.key, p.value, next);
1917
}
1918
1919
/**
1920
* Reset to initial default state. Called by clone and readObject.
1921
*/
1922
void reinitialize() {
1923
table = null;
1924
entrySet = null;
1925
keySet = null;
1926
values = null;
1927
modCount = 0;
1928
threshold = 0;
1929
size = 0;
1930
}
1931
1932
// Callbacks to allow LinkedHashMap post-actions
1933
void afterNodeAccess(Node<K,V> p) { }
1934
void afterNodeInsertion(boolean evict) { }
1935
void afterNodeRemoval(Node<K,V> p) { }
1936
1937
// Called only from writeObject, to ensure compatible ordering.
1938
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
1939
Node<K,V>[] tab;
1940
if (size > 0 && (tab = table) != null) {
1941
for (Node<K,V> e : tab) {
1942
for (; e != null; e = e.next) {
1943
s.writeObject(e.key);
1944
s.writeObject(e.value);
1945
}
1946
}
1947
}
1948
}
1949
1950
/* ------------------------------------------------------------ */
1951
// Tree bins
1952
1953
/**
1954
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
1955
* extends Node) so can be used as extension of either regular or
1956
* linked node.
1957
*/
1958
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
1959
TreeNode<K,V> parent; // red-black tree links
1960
TreeNode<K,V> left;
1961
TreeNode<K,V> right;
1962
TreeNode<K,V> prev; // needed to unlink next upon deletion
1963
boolean red;
1964
TreeNode(int hash, K key, V val, Node<K,V> next) {
1965
super(hash, key, val, next);
1966
}
1967
1968
/**
1969
* Returns root of tree containing this node.
1970
*/
1971
final TreeNode<K,V> root() {
1972
for (TreeNode<K,V> r = this, p;;) {
1973
if ((p = r.parent) == null)
1974
return r;
1975
r = p;
1976
}
1977
}
1978
1979
/**
1980
* Ensures that the given root is the first node of its bin.
1981
*/
1982
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
1983
int n;
1984
if (root != null && tab != null && (n = tab.length) > 0) {
1985
int index = (n - 1) & root.hash;
1986
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
1987
if (root != first) {
1988
Node<K,V> rn;
1989
tab[index] = root;
1990
TreeNode<K,V> rp = root.prev;
1991
if ((rn = root.next) != null)
1992
((TreeNode<K,V>)rn).prev = rp;
1993
if (rp != null)
1994
rp.next = rn;
1995
if (first != null)
1996
first.prev = root;
1997
root.next = first;
1998
root.prev = null;
1999
}
2000
assert checkInvariants(root);
2001
}
2002
}
2003
2004
/**
2005
* Finds the node starting at root p with the given hash and key.
2006
* The kc argument caches comparableClassFor(key) upon first use
2007
* comparing keys.
2008
*/
2009
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
2010
TreeNode<K,V> p = this;
2011
do {
2012
int ph, dir; K pk;
2013
TreeNode<K,V> pl = p.left, pr = p.right, q;
2014
if ((ph = p.hash) > h)
2015
p = pl;
2016
else if (ph < h)
2017
p = pr;
2018
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
2019
return p;
2020
else if (pl == null)
2021
p = pr;
2022
else if (pr == null)
2023
p = pl;
2024
else if ((kc != null ||
2025
(kc = comparableClassFor(k)) != null) &&
2026
(dir = compareComparables(kc, k, pk)) != 0)
2027
p = (dir < 0) ? pl : pr;
2028
else if ((q = pr.find(h, k, kc)) != null)
2029
return q;
2030
else
2031
p = pl;
2032
} while (p != null);
2033
return null;
2034
}
2035
2036
/**
2037
* Calls find for root node.
2038
*/
2039
final TreeNode<K,V> getTreeNode(int h, Object k) {
2040
return ((parent != null) ? root() : this).find(h, k, null);
2041
}
2042
2043
/**
2044
* Tie-breaking utility for ordering insertions when equal
2045
* hashCodes and non-comparable. We don't require a total
2046
* order, just a consistent insertion rule to maintain
2047
* equivalence across rebalancings. Tie-breaking further than
2048
* necessary simplifies testing a bit.
2049
*/
2050
static int tieBreakOrder(Object a, Object b) {
2051
int d;
2052
if (a == null || b == null ||
2053
(d = a.getClass().getName().
2054
compareTo(b.getClass().getName())) == 0)
2055
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2056
-1 : 1);
2057
return d;
2058
}
2059
2060
/**
2061
* Forms tree of the nodes linked from this node.
2062
*/
2063
final void treeify(Node<K,V>[] tab) {
2064
TreeNode<K,V> root = null;
2065
for (TreeNode<K,V> x = this, next; x != null; x = next) {
2066
next = (TreeNode<K,V>)x.next;
2067
x.left = x.right = null;
2068
if (root == null) {
2069
x.parent = null;
2070
x.red = false;
2071
root = x;
2072
}
2073
else {
2074
K k = x.key;
2075
int h = x.hash;
2076
Class<?> kc = null;
2077
for (TreeNode<K,V> p = root;;) {
2078
int dir, ph;
2079
K pk = p.key;
2080
if ((ph = p.hash) > h)
2081
dir = -1;
2082
else if (ph < h)
2083
dir = 1;
2084
else if ((kc == null &&
2085
(kc = comparableClassFor(k)) == null) ||
2086
(dir = compareComparables(kc, k, pk)) == 0)
2087
dir = tieBreakOrder(k, pk);
2088
2089
TreeNode<K,V> xp = p;
2090
if ((p = (dir <= 0) ? p.left : p.right) == null) {
2091
x.parent = xp;
2092
if (dir <= 0)
2093
xp.left = x;
2094
else
2095
xp.right = x;
2096
root = balanceInsertion(root, x);
2097
break;
2098
}
2099
}
2100
}
2101
}
2102
moveRootToFront(tab, root);
2103
}
2104
2105
/**
2106
* Returns a list of non-TreeNodes replacing those linked from
2107
* this node.
2108
*/
2109
final Node<K,V> untreeify(HashMap<K,V> map) {
2110
Node<K,V> hd = null, tl = null;
2111
for (Node<K,V> q = this; q != null; q = q.next) {
2112
Node<K,V> p = map.replacementNode(q, null);
2113
if (tl == null)
2114
hd = p;
2115
else
2116
tl.next = p;
2117
tl = p;
2118
}
2119
return hd;
2120
}
2121
2122
/**
2123
* Tree version of putVal.
2124
*/
2125
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
2126
int h, K k, V v) {
2127
Class<?> kc = null;
2128
boolean searched = false;
2129
TreeNode<K,V> root = (parent != null) ? root() : this;
2130
for (TreeNode<K,V> p = root;;) {
2131
int dir, ph; K pk;
2132
if ((ph = p.hash) > h)
2133
dir = -1;
2134
else if (ph < h)
2135
dir = 1;
2136
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
2137
return p;
2138
else if ((kc == null &&
2139
(kc = comparableClassFor(k)) == null) ||
2140
(dir = compareComparables(kc, k, pk)) == 0) {
2141
if (!searched) {
2142
TreeNode<K,V> q, ch;
2143
searched = true;
2144
if (((ch = p.left) != null &&
2145
(q = ch.find(h, k, kc)) != null) ||
2146
((ch = p.right) != null &&
2147
(q = ch.find(h, k, kc)) != null))
2148
return q;
2149
}
2150
dir = tieBreakOrder(k, pk);
2151
}
2152
2153
TreeNode<K,V> xp = p;
2154
if ((p = (dir <= 0) ? p.left : p.right) == null) {
2155
Node<K,V> xpn = xp.next;
2156
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
2157
if (dir <= 0)
2158
xp.left = x;
2159
else
2160
xp.right = x;
2161
xp.next = x;
2162
x.parent = x.prev = xp;
2163
if (xpn != null)
2164
((TreeNode<K,V>)xpn).prev = x;
2165
moveRootToFront(tab, balanceInsertion(root, x));
2166
return null;
2167
}
2168
}
2169
}
2170
2171
/**
2172
* Removes the given node, that must be present before this call.
2173
* This is messier than typical red-black deletion code because we
2174
* cannot swap the contents of an interior node with a leaf
2175
* successor that is pinned by "next" pointers that are accessible
2176
* independently during traversal. So instead we swap the tree
2177
* linkages. If the current tree appears to have too few nodes,
2178
* the bin is converted back to a plain bin. (The test triggers
2179
* somewhere between 2 and 6 nodes, depending on tree structure).
2180
*/
2181
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
2182
boolean movable) {
2183
int n;
2184
if (tab == null || (n = tab.length) == 0)
2185
return;
2186
int index = (n - 1) & hash;
2187
TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
2188
TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
2189
if (pred == null)
2190
tab[index] = first = succ;
2191
else
2192
pred.next = succ;
2193
if (succ != null)
2194
succ.prev = pred;
2195
if (first == null)
2196
return;
2197
if (root.parent != null)
2198
root = root.root();
2199
if (root == null
2200
|| (movable
2201
&& (root.right == null
2202
|| (rl = root.left) == null
2203
|| rl.left == null))) {
2204
tab[index] = first.untreeify(map); // too small
2205
return;
2206
}
2207
TreeNode<K,V> p = this, pl = left, pr = right, replacement;
2208
if (pl != null && pr != null) {
2209
TreeNode<K,V> s = pr, sl;
2210
while ((sl = s.left) != null) // find successor
2211
s = sl;
2212
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2213
TreeNode<K,V> sr = s.right;
2214
TreeNode<K,V> pp = p.parent;
2215
if (s == pr) { // p was s's direct parent
2216
p.parent = s;
2217
s.right = p;
2218
}
2219
else {
2220
TreeNode<K,V> sp = s.parent;
2221
if ((p.parent = sp) != null) {
2222
if (s == sp.left)
2223
sp.left = p;
2224
else
2225
sp.right = p;
2226
}
2227
if ((s.right = pr) != null)
2228
pr.parent = s;
2229
}
2230
p.left = null;
2231
if ((p.right = sr) != null)
2232
sr.parent = p;
2233
if ((s.left = pl) != null)
2234
pl.parent = s;
2235
if ((s.parent = pp) == null)
2236
root = s;
2237
else if (p == pp.left)
2238
pp.left = s;
2239
else
2240
pp.right = s;
2241
if (sr != null)
2242
replacement = sr;
2243
else
2244
replacement = p;
2245
}
2246
else if (pl != null)
2247
replacement = pl;
2248
else if (pr != null)
2249
replacement = pr;
2250
else
2251
replacement = p;
2252
if (replacement != p) {
2253
TreeNode<K,V> pp = replacement.parent = p.parent;
2254
if (pp == null)
2255
(root = replacement).red = false;
2256
else if (p == pp.left)
2257
pp.left = replacement;
2258
else
2259
pp.right = replacement;
2260
p.left = p.right = p.parent = null;
2261
}
2262
2263
TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
2264
2265
if (replacement == p) { // detach
2266
TreeNode<K,V> pp = p.parent;
2267
p.parent = null;
2268
if (pp != null) {
2269
if (p == pp.left)
2270
pp.left = null;
2271
else if (p == pp.right)
2272
pp.right = null;
2273
}
2274
}
2275
if (movable)
2276
moveRootToFront(tab, r);
2277
}
2278
2279
/**
2280
* Splits nodes in a tree bin into lower and upper tree bins,
2281
* or untreeifies if now too small. Called only from resize;
2282
* see above discussion about split bits and indices.
2283
*
2284
* @param map the map
2285
* @param tab the table for recording bin heads
2286
* @param index the index of the table being split
2287
* @param bit the bit of hash to split on
2288
*/
2289
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
2290
TreeNode<K,V> b = this;
2291
// Relink into lo and hi lists, preserving order
2292
TreeNode<K,V> loHead = null, loTail = null;
2293
TreeNode<K,V> hiHead = null, hiTail = null;
2294
int lc = 0, hc = 0;
2295
for (TreeNode<K,V> e = b, next; e != null; e = next) {
2296
next = (TreeNode<K,V>)e.next;
2297
e.next = null;
2298
if ((e.hash & bit) == 0) {
2299
if ((e.prev = loTail) == null)
2300
loHead = e;
2301
else
2302
loTail.next = e;
2303
loTail = e;
2304
++lc;
2305
}
2306
else {
2307
if ((e.prev = hiTail) == null)
2308
hiHead = e;
2309
else
2310
hiTail.next = e;
2311
hiTail = e;
2312
++hc;
2313
}
2314
}
2315
2316
if (loHead != null) {
2317
if (lc <= UNTREEIFY_THRESHOLD)
2318
tab[index] = loHead.untreeify(map);
2319
else {
2320
tab[index] = loHead;
2321
if (hiHead != null) // (else is already treeified)
2322
loHead.treeify(tab);
2323
}
2324
}
2325
if (hiHead != null) {
2326
if (hc <= UNTREEIFY_THRESHOLD)
2327
tab[index + bit] = hiHead.untreeify(map);
2328
else {
2329
tab[index + bit] = hiHead;
2330
if (loHead != null)
2331
hiHead.treeify(tab);
2332
}
2333
}
2334
}
2335
2336
/* ------------------------------------------------------------ */
2337
// Red-black tree methods, all adapted from CLR
2338
2339
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2340
TreeNode<K,V> p) {
2341
TreeNode<K,V> r, pp, rl;
2342
if (p != null && (r = p.right) != null) {
2343
if ((rl = p.right = r.left) != null)
2344
rl.parent = p;
2345
if ((pp = r.parent = p.parent) == null)
2346
(root = r).red = false;
2347
else if (pp.left == p)
2348
pp.left = r;
2349
else
2350
pp.right = r;
2351
r.left = p;
2352
p.parent = r;
2353
}
2354
return root;
2355
}
2356
2357
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2358
TreeNode<K,V> p) {
2359
TreeNode<K,V> l, pp, lr;
2360
if (p != null && (l = p.left) != null) {
2361
if ((lr = p.left = l.right) != null)
2362
lr.parent = p;
2363
if ((pp = l.parent = p.parent) == null)
2364
(root = l).red = false;
2365
else if (pp.right == p)
2366
pp.right = l;
2367
else
2368
pp.left = l;
2369
l.right = p;
2370
p.parent = l;
2371
}
2372
return root;
2373
}
2374
2375
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2376
TreeNode<K,V> x) {
2377
x.red = true;
2378
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2379
if ((xp = x.parent) == null) {
2380
x.red = false;
2381
return x;
2382
}
2383
else if (!xp.red || (xpp = xp.parent) == null)
2384
return root;
2385
if (xp == (xppl = xpp.left)) {
2386
if ((xppr = xpp.right) != null && xppr.red) {
2387
xppr.red = false;
2388
xp.red = false;
2389
xpp.red = true;
2390
x = xpp;
2391
}
2392
else {
2393
if (x == xp.right) {
2394
root = rotateLeft(root, x = xp);
2395
xpp = (xp = x.parent) == null ? null : xp.parent;
2396
}
2397
if (xp != null) {
2398
xp.red = false;
2399
if (xpp != null) {
2400
xpp.red = true;
2401
root = rotateRight(root, xpp);
2402
}
2403
}
2404
}
2405
}
2406
else {
2407
if (xppl != null && xppl.red) {
2408
xppl.red = false;
2409
xp.red = false;
2410
xpp.red = true;
2411
x = xpp;
2412
}
2413
else {
2414
if (x == xp.left) {
2415
root = rotateRight(root, x = xp);
2416
xpp = (xp = x.parent) == null ? null : xp.parent;
2417
}
2418
if (xp != null) {
2419
xp.red = false;
2420
if (xpp != null) {
2421
xpp.red = true;
2422
root = rotateLeft(root, xpp);
2423
}
2424
}
2425
}
2426
}
2427
}
2428
}
2429
2430
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2431
TreeNode<K,V> x) {
2432
for (TreeNode<K,V> xp, xpl, xpr;;) {
2433
if (x == null || x == root)
2434
return root;
2435
else if ((xp = x.parent) == null) {
2436
x.red = false;
2437
return x;
2438
}
2439
else if (x.red) {
2440
x.red = false;
2441
return root;
2442
}
2443
else if ((xpl = xp.left) == x) {
2444
if ((xpr = xp.right) != null && xpr.red) {
2445
xpr.red = false;
2446
xp.red = true;
2447
root = rotateLeft(root, xp);
2448
xpr = (xp = x.parent) == null ? null : xp.right;
2449
}
2450
if (xpr == null)
2451
x = xp;
2452
else {
2453
TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2454
if ((sr == null || !sr.red) &&
2455
(sl == null || !sl.red)) {
2456
xpr.red = true;
2457
x = xp;
2458
}
2459
else {
2460
if (sr == null || !sr.red) {
2461
if (sl != null)
2462
sl.red = false;
2463
xpr.red = true;
2464
root = rotateRight(root, xpr);
2465
xpr = (xp = x.parent) == null ?
2466
null : xp.right;
2467
}
2468
if (xpr != null) {
2469
xpr.red = (xp == null) ? false : xp.red;
2470
if ((sr = xpr.right) != null)
2471
sr.red = false;
2472
}
2473
if (xp != null) {
2474
xp.red = false;
2475
root = rotateLeft(root, xp);
2476
}
2477
x = root;
2478
}
2479
}
2480
}
2481
else { // symmetric
2482
if (xpl != null && xpl.red) {
2483
xpl.red = false;
2484
xp.red = true;
2485
root = rotateRight(root, xp);
2486
xpl = (xp = x.parent) == null ? null : xp.left;
2487
}
2488
if (xpl == null)
2489
x = xp;
2490
else {
2491
TreeNode<K,V> sl = xpl.left, sr = xpl.right;
2492
if ((sl == null || !sl.red) &&
2493
(sr == null || !sr.red)) {
2494
xpl.red = true;
2495
x = xp;
2496
}
2497
else {
2498
if (sl == null || !sl.red) {
2499
if (sr != null)
2500
sr.red = false;
2501
xpl.red = true;
2502
root = rotateLeft(root, xpl);
2503
xpl = (xp = x.parent) == null ?
2504
null : xp.left;
2505
}
2506
if (xpl != null) {
2507
xpl.red = (xp == null) ? false : xp.red;
2508
if ((sl = xpl.left) != null)
2509
sl.red = false;
2510
}
2511
if (xp != null) {
2512
xp.red = false;
2513
root = rotateRight(root, xp);
2514
}
2515
x = root;
2516
}
2517
}
2518
}
2519
}
2520
}
2521
2522
/**
2523
* Recursive invariant check
2524
*/
2525
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
2526
TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
2527
tb = t.prev, tn = (TreeNode<K,V>)t.next;
2528
if (tb != null && tb.next != t)
2529
return false;
2530
if (tn != null && tn.prev != t)
2531
return false;
2532
if (tp != null && t != tp.left && t != tp.right)
2533
return false;
2534
if (tl != null && (tl.parent != t || tl.hash > t.hash))
2535
return false;
2536
if (tr != null && (tr.parent != t || tr.hash < t.hash))
2537
return false;
2538
if (t.red && tl != null && tl.red && tr != null && tr.red)
2539
return false;
2540
if (tl != null && !checkInvariants(tl))
2541
return false;
2542
if (tr != null && !checkInvariants(tr))
2543
return false;
2544
return true;
2545
}
2546
}
2547
2548
}
2549
2550