1 /*
2 * Copyright (c) 1997, 2025, 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("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 * @apiNote
437 * To create a {@code HashMap} with an initial capacity that accommodates
438 * an expected number of mappings, use {@link #newHashMap(int) newHashMap}.
439 *
440 * @param initialCapacity the initial capacity
441 * @param loadFactor the load factor
442 * @throws IllegalArgumentException if the initial capacity is negative
443 * or the load factor is nonpositive
444 */
445 public HashMap(int initialCapacity, float loadFactor) {
446 if (initialCapacity < 0)
447 throw new IllegalArgumentException("Illegal initial capacity: " +
448 initialCapacity);
449 if (initialCapacity > MAXIMUM_CAPACITY)
450 initialCapacity = MAXIMUM_CAPACITY;
451 if (loadFactor <= 0 || Float.isNaN(loadFactor))
452 throw new IllegalArgumentException("Illegal load factor: " +
453 loadFactor);
454 this.loadFactor = loadFactor;
455 this.threshold = tableSizeFor(initialCapacity);
456 }
457
458 /**
459 * Constructs an empty {@code HashMap} with the specified initial
460 * capacity and the default load factor (0.75).
461 *
462 * @apiNote
463 * To create a {@code HashMap} with an initial capacity that accommodates
464 * an expected number of mappings, use {@link #newHashMap(int) newHashMap}.
465 *
466 * @param initialCapacity the initial capacity.
467 * @throws IllegalArgumentException if the initial capacity is negative.
468 */
469 public HashMap(int initialCapacity) {
470 this(initialCapacity, DEFAULT_LOAD_FACTOR);
471 }
472
473 /**
474 * Constructs an empty {@code HashMap} with the default initial capacity
475 * (16) and the default load factor (0.75).
476 */
477 public HashMap() {
478 this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
479 }
480
481 /**
482 * Constructs a new {@code HashMap} with the same mappings as the
483 * specified {@code Map}. The {@code HashMap} is created with
484 * default load factor (0.75) and an initial capacity sufficient to
485 * hold the mappings in the specified {@code Map}.
486 *
487 * @param m the map whose mappings are to be placed in this map
488 * @throws NullPointerException if the specified map is null
489 */
490 @SuppressWarnings("this-escape")
491 public HashMap(Map<? extends K, ? extends V> m) {
492 this.loadFactor = DEFAULT_LOAD_FACTOR;
493 putMapEntries(m, false);
494 }
495
496 /**
497 * Implements Map.putAll and Map constructor.
498 *
499 * @param m the map
500 * @param evict false when initially constructing this map, else
501 * true (relayed to method afterNodeInsertion).
502 */
503 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
504 int s = m.size();
505 if (s > 0) {
506 if (table == null) { // pre-size
507 double dt = Math.ceil(s / (double)loadFactor);
508 int t = ((dt < (double)MAXIMUM_CAPACITY) ?
509 (int)dt : MAXIMUM_CAPACITY);
510 if (t > threshold)
511 threshold = tableSizeFor(t);
512 } else {
513 // Because of linked-list bucket constraints, we cannot
514 // expand all at once, but can reduce total resize
515 // effort by repeated doubling now vs later
516 while (s > threshold && table.length < MAXIMUM_CAPACITY)
517 resize();
518 }
519
520 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
521 K key = e.getKey();
522 V value = e.getValue();
523 putVal(hash(key), key, value, false, evict);
524 }
525 }
526 }
527
528 /**
529 * Returns the number of key-value mappings in this map.
530 *
531 * @return the number of key-value mappings in this map
532 */
533 public int size() {
534 return size;
535 }
536
537 /**
538 * Returns {@code true} if this map contains no key-value mappings.
539 *
540 * @return {@code true} if this map contains no key-value mappings
541 */
542 public boolean isEmpty() {
543 return size == 0;
544 }
545
546 /**
547 * Returns the value to which the specified key is mapped,
548 * or {@code null} if this map contains no mapping for the key.
549 *
550 * <p>More formally, if this map contains a mapping from a key
551 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
552 * key.equals(k))}, then this method returns {@code v}; otherwise
553 * it returns {@code null}. (There can be at most one such mapping.)
554 *
555 * <p>A return value of {@code null} does not <i>necessarily</i>
556 * indicate that the map contains no mapping for the key; it's also
557 * possible that the map explicitly maps the key to {@code null}.
558 * The {@link #containsKey containsKey} operation may be used to
559 * distinguish these two cases.
560 *
561 * @see #put(Object, Object)
562 */
563 public V get(Object key) {
564 Node<K,V> e;
565 return (e = getNode(key)) == null ? null : e.value;
566 }
567
568 /**
569 * Implements Map.get and related methods.
570 *
571 * @param key the key
572 * @return the node, or null if none
573 */
574 final Node<K,V> getNode(Object key) {
575 Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
576 if ((tab = table) != null && (n = tab.length) > 0 &&
577 (first = tab[(n - 1) & (hash = hash(key))]) != null) {
578 if (first.hash == hash && // always check first node
579 ((k = first.key) == key || (key != null && key.equals(k))))
580 return first;
581 if ((e = first.next) != null) {
582 if (first instanceof TreeNode)
583 return ((TreeNode<K,V>)first).getTreeNode(hash, key);
584 do {
585 if (e.hash == hash &&
586 ((k = e.key) == key || (key != null && key.equals(k))))
587 return e;
588 } while ((e = e.next) != null);
589 }
590 }
591 return null;
592 }
593
594 /**
595 * Returns {@code true} if this map contains a mapping for the
596 * specified key.
597 *
598 * @param key The key whose presence in this map is to be tested
599 * @return {@code true} if this map contains a mapping for the specified
600 * key.
601 */
602 public boolean containsKey(Object key) {
603 return getNode(key) != null;
604 }
605
606 /**
607 * Associates the specified value with the specified key in this map.
608 * If the map previously contained a mapping for the key, the old
609 * value is replaced.
610 *
611 * @param key key with which the specified value is to be associated
612 * @param value value to be associated with the specified key
613 * @return the previous value associated with {@code key}, or
614 * {@code null} if there was no mapping for {@code key}.
615 * (A {@code null} return can also indicate that the map
616 * previously associated {@code null} with {@code key}.)
617 */
618 public V put(K key, V value) {
619 return putVal(hash(key), key, value, false, true);
620 }
621
622 /**
623 * Implements Map.put and related methods.
624 *
625 * @param hash hash for key
626 * @param key the key
627 * @param value the value to put
628 * @param onlyIfAbsent if true, don't change existing value
629 * @param evict if false, the table is in creation mode.
630 * @return previous value, or null if none
631 */
632 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
633 boolean evict) {
634 Node<K,V>[] tab; Node<K,V> p; int n, i;
635 if ((tab = table) == null || (n = tab.length) == 0)
636 n = (tab = resize()).length;
637 if ((p = tab[i = (n - 1) & hash]) == null)
638 tab[i] = newNode(hash, key, value, null);
639 else {
640 Node<K,V> e; K k;
641 if (p.hash == hash &&
642 ((k = p.key) == key || (key != null && key.equals(k))))
643 e = p;
644 else if (p instanceof TreeNode)
645 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
646 else {
647 for (int binCount = 0; ; ++binCount) {
648 if ((e = p.next) == null) {
649 p.next = newNode(hash, key, value, null);
650 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
651 treeifyBin(tab, hash);
652 break;
653 }
654 if (e.hash == hash &&
655 ((k = e.key) == key || (key != null && key.equals(k))))
656 break;
657 p = e;
658 }
659 }
660 if (e != null) { // existing mapping for key
661 V oldValue = e.value;
662 if (!onlyIfAbsent || oldValue == null)
663 e.value = value;
664 afterNodeAccess(e);
665 return oldValue;
666 }
667 }
668 ++modCount;
669 if (++size > threshold)
670 resize();
671 afterNodeInsertion(evict);
672 return null;
673 }
674
675 /**
676 * Initializes or doubles table size. If null, allocates in
677 * accord with initial capacity target held in field threshold.
678 * Otherwise, because we are using power-of-two expansion, the
679 * elements from each bin must either stay at same index, or move
680 * with a power of two offset in the new table.
681 *
682 * @return the table
683 */
684 final Node<K,V>[] resize() {
685 Node<K,V>[] oldTab = table;
686 int oldCap = (oldTab == null) ? 0 : oldTab.length;
687 int oldThr = threshold;
688 int newCap, newThr = 0;
689 if (oldCap > 0) {
690 if (oldCap >= MAXIMUM_CAPACITY) {
691 threshold = Integer.MAX_VALUE;
692 return oldTab;
693 }
694 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
695 oldCap >= DEFAULT_INITIAL_CAPACITY)
696 newThr = oldThr << 1; // double threshold
697 }
698 else if (oldThr > 0) // initial capacity was placed in threshold
699 newCap = oldThr;
700 else { // zero initial threshold signifies using defaults
701 newCap = DEFAULT_INITIAL_CAPACITY;
702 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
703 }
704 if (newThr == 0) {
705 float ft = (float)newCap * loadFactor;
706 newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
707 (int)ft : Integer.MAX_VALUE);
708 }
709 threshold = newThr;
710 @SuppressWarnings({"rawtypes","unchecked"})
711 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
712 table = newTab;
713 if (oldTab != null) {
714 for (int j = 0; j < oldCap; ++j) {
715 Node<K,V> e;
716 if ((e = oldTab[j]) != null) {
717 oldTab[j] = null;
718 if (e.next == null)
719 newTab[e.hash & (newCap - 1)] = e;
720 else if (e instanceof TreeNode)
721 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
722 else { // preserve order
723 Node<K,V> loHead = null, loTail = null;
724 Node<K,V> hiHead = null, hiTail = null;
725 Node<K,V> next;
726 do {
727 next = e.next;
728 if ((e.hash & oldCap) == 0) {
729 if (loTail == null)
730 loHead = e;
731 else
732 loTail.next = e;
733 loTail = e;
734 }
735 else {
736 if (hiTail == null)
737 hiHead = e;
738 else
739 hiTail.next = e;
740 hiTail = e;
741 }
742 } while ((e = next) != null);
743 if (loTail != null) {
744 loTail.next = null;
745 newTab[j] = loHead;
746 }
747 if (hiTail != null) {
748 hiTail.next = null;
749 newTab[j + oldCap] = hiHead;
750 }
751 }
752 }
753 }
754 }
755 return newTab;
756 }
757
758 /**
759 * Replaces all linked nodes in bin at index for given hash unless
760 * table is too small, in which case resizes instead.
761 */
762 final void treeifyBin(Node<K,V>[] tab, int hash) {
763 int n, index; Node<K,V> e;
764 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
765 resize();
766 else if ((e = tab[index = (n - 1) & hash]) != null) {
767 TreeNode<K,V> hd = null, tl = null;
768 do {
769 TreeNode<K,V> p = replacementTreeNode(e, null);
770 if (tl == null)
771 hd = p;
772 else {
773 p.prev = tl;
774 tl.next = p;
775 }
776 tl = p;
777 } while ((e = e.next) != null);
778 if ((tab[index] = hd) != null)
779 hd.treeify(tab);
780 }
781 }
782
783 /**
784 * Copies all of the mappings from the specified map to this map.
785 * These mappings will replace any mappings that this map had for
786 * any of the keys currently in the specified map.
787 *
788 * @param m mappings to be stored in this map
789 * @throws NullPointerException if the specified map is null
790 */
791 public void putAll(Map<? extends K, ? extends V> m) {
792 putMapEntries(m, true);
793 }
794
795 /**
796 * Removes the mapping for the specified key from this map if present.
797 *
798 * @param key key whose mapping is to be removed from the map
799 * @return the previous value associated with {@code key}, or
800 * {@code null} if there was no mapping for {@code key}.
801 * (A {@code null} return can also indicate that the map
802 * previously associated {@code null} with {@code key}.)
803 */
804 public V remove(Object key) {
805 Node<K,V> e;
806 return (e = removeNode(hash(key), key, null, false, true)) == null ?
807 null : e.value;
808 }
809
810 /**
811 * Implements Map.remove and related methods.
812 *
813 * @param hash hash for key
814 * @param key the key
815 * @param value the value to match if matchValue, else ignored
816 * @param matchValue if true only remove if value is equal
817 * @param movable if false do not move other nodes while removing
818 * @return the node, or null if none
819 */
820 final Node<K,V> removeNode(int hash, Object key, Object value,
821 boolean matchValue, boolean movable) {
822 Node<K,V>[] tab; Node<K,V> p; int n, index;
823 if ((tab = table) != null && (n = tab.length) > 0 &&
824 (p = tab[index = (n - 1) & hash]) != null) {
825 Node<K,V> node = null, e; K k; V v;
826 if (p.hash == hash &&
827 ((k = p.key) == key || (key != null && key.equals(k))))
828 node = p;
829 else if ((e = p.next) != null) {
830 if (p instanceof TreeNode)
831 node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
832 else {
833 do {
834 if (e.hash == hash &&
835 ((k = e.key) == key ||
836 (key != null && key.equals(k)))) {
837 node = e;
838 break;
839 }
840 p = e;
841 } while ((e = e.next) != null);
842 }
843 }
844 if (node != null && (!matchValue || (v = node.value) == value ||
845 (value != null && value.equals(v)))) {
846 if (node instanceof TreeNode)
847 ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
848 else if (node == p)
849 tab[index] = node.next;
850 else
851 p.next = node.next;
852 ++modCount;
853 --size;
854 afterNodeRemoval(node);
855 return node;
856 }
857 }
858 return null;
859 }
860
861 /**
862 * Removes all of the mappings from this map.
863 * The map will be empty after this call returns.
864 */
865 public void clear() {
866 Node<K,V>[] tab;
867 modCount++;
868 if ((tab = table) != null && size > 0) {
869 size = 0;
870 for (int i = 0; i < tab.length; ++i)
871 tab[i] = null;
872 }
873 }
874
875 /**
876 * Returns {@code true} if this map maps one or more keys to the
877 * specified value.
878 *
879 * @param value value whose presence in this map is to be tested
880 * @return {@code true} if this map maps one or more keys to the
881 * specified value
882 */
883 public boolean containsValue(Object value) {
884 Node<K,V>[] tab; V v;
885 if ((tab = table) != null && size > 0) {
886 for (Node<K,V> e : tab) {
887 for (; e != null; e = e.next) {
888 if ((v = e.value) == value ||
889 (value != null && value.equals(v)))
890 return true;
891 }
892 }
893 }
894 return false;
895 }
896
897 /**
898 * Returns a {@link Set} view of the keys contained in this map.
899 * The set is backed by the map, so changes to the map are
900 * reflected in the set, and vice-versa. If the map is modified
901 * while an iteration over the set is in progress (except through
902 * the iterator's own {@code remove} operation), the results of
903 * the iteration are undefined. The set supports element removal,
904 * which removes the corresponding mapping from the map, via the
905 * {@code Iterator.remove}, {@code Set.remove},
906 * {@code removeAll}, {@code retainAll}, and {@code clear}
907 * operations. It does not support the {@code add} or {@code addAll}
908 * operations.
909 *
910 * @return a set view of the keys contained in this map
911 */
912 public Set<K> keySet() {
913 Set<K> ks = keySet;
914 if (ks == null) {
915 ks = new KeySet();
916 keySet = ks;
917 }
918 return ks;
919 }
920
921 /**
922 * Prepares the array for {@link Collection#toArray(Object[])} implementation.
923 * If supplied array is smaller than this map size, a new array is allocated.
924 * If supplied array is bigger than this map size, a null is written at size index.
925 *
926 * @param a an original array passed to {@code toArray()} method
927 * @param <T> type of array elements
928 * @return an array ready to be filled and returned from {@code toArray()} method.
929 */
930 @SuppressWarnings("unchecked")
931 final <T> T[] prepareArray(T[] a) {
932 int size = this.size;
933 if (a.length < size) {
934 return (T[]) java.lang.reflect.Array
935 .newInstance(a.getClass().getComponentType(), size);
936 }
937 if (a.length > size) {
938 a[size] = null;
939 }
940 return a;
941 }
942
943 /**
944 * Fills an array with this map keys and returns it. This method assumes
945 * that input array is big enough to fit all the keys. Use
946 * {@link #prepareArray(Object[])} to ensure this.
947 *
948 * @param a an array to fill
949 * @param <T> type of array elements
950 * @return supplied array
951 */
952 <T> T[] keysToArray(T[] a) {
953 Object[] r = a;
954 Node<K,V>[] tab;
955 int idx = 0;
956 if (size > 0 && (tab = table) != null) {
957 for (Node<K,V> e : tab) {
958 for (; e != null; e = e.next) {
959 r[idx++] = e.key;
960 }
961 }
962 }
963 return a;
964 }
965
966 /**
967 * Fills an array with this map values and returns it. This method assumes
968 * that input array is big enough to fit all the values. Use
969 * {@link #prepareArray(Object[])} to ensure this.
970 *
971 * @param a an array to fill
972 * @param <T> type of array elements
973 * @return supplied array
974 */
975 <T> T[] valuesToArray(T[] a) {
976 Object[] r = a;
977 Node<K,V>[] tab;
978 int idx = 0;
979 if (size > 0 && (tab = table) != null) {
980 for (Node<K,V> e : tab) {
981 for (; e != null; e = e.next) {
982 r[idx++] = e.value;
983 }
984 }
985 }
986 return a;
987 }
988
989 final class KeySet extends AbstractSet<K> {
990 public final int size() { return size; }
991 public final void clear() { HashMap.this.clear(); }
992 public final Iterator<K> iterator() { return new KeyIterator(); }
993 public final boolean contains(Object o) { return containsKey(o); }
994 public final boolean remove(Object key) {
995 return removeNode(hash(key), key, null, false, true) != null;
996 }
997 public final Spliterator<K> spliterator() {
998 return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
999 }
1000
1001 public Object[] toArray() {
1002 return keysToArray(new Object[size]);
1003 }
1004
1005 public <T> T[] toArray(T[] a) {
1006 return keysToArray(prepareArray(a));
1007 }
1008
1009 public final void forEach(Consumer<? super K> action) {
1010 Node<K,V>[] tab;
1011 if (action == null)
1012 throw new NullPointerException();
1013 if (size > 0 && (tab = table) != null) {
1014 int mc = modCount;
1015 for (Node<K,V> e : tab) {
1016 for (; e != null; e = e.next)
1017 action.accept(e.key);
1018 }
1019 if (modCount != mc)
1020 throw new ConcurrentModificationException();
1021 }
1022 }
1023 }
1024
1025 /**
1026 * Returns a {@link Collection} view of the values contained in this map.
1027 * The collection is backed by the map, so changes to the map are
1028 * reflected in the collection, and vice-versa. If the map is
1029 * modified while an iteration over the collection is in progress
1030 * (except through the iterator's own {@code remove} operation),
1031 * the results of the iteration are undefined. The collection
1032 * supports element removal, which removes the corresponding
1033 * mapping from the map, via the {@code Iterator.remove},
1034 * {@code Collection.remove}, {@code removeAll},
1035 * {@code retainAll} and {@code clear} operations. It does not
1036 * support the {@code add} or {@code addAll} operations.
1037 *
1038 * @return a view of the values contained in this map
1039 */
1040 public Collection<V> values() {
1041 Collection<V> vs = values;
1042 if (vs == null) {
1043 vs = new Values();
1044 values = vs;
1045 }
1046 return vs;
1047 }
1048
1049 final class Values extends AbstractCollection<V> {
1050 public final int size() { return size; }
1051 public final void clear() { HashMap.this.clear(); }
1052 public final Iterator<V> iterator() { return new ValueIterator(); }
1053 public final boolean contains(Object o) { return containsValue(o); }
1054 public final Spliterator<V> spliterator() {
1055 return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
1056 }
1057
1058 public Object[] toArray() {
1059 return valuesToArray(new Object[size]);
1060 }
1061
1062 public <T> T[] toArray(T[] a) {
1063 return valuesToArray(prepareArray(a));
1064 }
1065
1066 public final void forEach(Consumer<? super V> action) {
1067 Node<K,V>[] tab;
1068 if (action == null)
1069 throw new NullPointerException();
1070 if (size > 0 && (tab = table) != null) {
1071 int mc = modCount;
1072 for (Node<K,V> e : tab) {
1073 for (; e != null; e = e.next)
1074 action.accept(e.value);
1075 }
1076 if (modCount != mc)
1077 throw new ConcurrentModificationException();
1078 }
1079 }
1080 }
1081
1082 /**
1083 * Returns a {@link Set} view of the mappings contained in this map.
1084 * The set is backed by the map, so changes to the map are
1085 * reflected in the set, and vice-versa. If the map is modified
1086 * while an iteration over the set is in progress (except through
1087 * the iterator's own {@code remove} operation, or through the
1088 * {@code setValue} operation on a map entry returned by the
1089 * iterator) the results of the iteration are undefined. The set
1090 * supports element removal, which removes the corresponding
1091 * mapping from the map, via the {@code Iterator.remove},
1092 * {@code Set.remove}, {@code removeAll}, {@code retainAll} and
1093 * {@code clear} operations. It does not support the
1094 * {@code add} or {@code addAll} operations.
1095 *
1096 * @return a set view of the mappings contained in this map
1097 */
1098 public Set<Map.Entry<K,V>> entrySet() {
1099 Set<Map.Entry<K,V>> es;
1100 return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
1101 }
1102
1103 final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1104 public final int size() { return size; }
1105 public final void clear() { HashMap.this.clear(); }
1106 public final Iterator<Map.Entry<K,V>> iterator() {
1107 return new EntryIterator();
1108 }
1109 public final boolean contains(Object o) {
1110 if (!(o instanceof Map.Entry<?, ?> e))
1111 return false;
1112 Object key = e.getKey();
1113 Node<K,V> candidate = getNode(key);
1114 return candidate != null && candidate.equals(e);
1115 }
1116 public final boolean remove(Object o) {
1117 if (o instanceof Map.Entry<?, ?> e) {
1118 Object key = e.getKey();
1119 Object value = e.getValue();
1120 return removeNode(hash(key), key, value, true, true) != null;
1121 }
1122 return false;
1123 }
1124 public final Spliterator<Map.Entry<K,V>> spliterator() {
1125 return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
1126 }
1127 public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
1128 Node<K,V>[] tab;
1129 if (action == null)
1130 throw new NullPointerException();
1131 if (size > 0 && (tab = table) != null) {
1132 int mc = modCount;
1133 for (Node<K,V> e : tab) {
1134 for (; e != null; e = e.next)
1135 action.accept(e);
1136 }
1137 if (modCount != mc)
1138 throw new ConcurrentModificationException();
1139 }
1140 }
1141 }
1142
1143 // Overrides of JDK8 Map extension methods
1144
1145 @Override
1146 public V getOrDefault(Object key, V defaultValue) {
1147 Node<K,V> e;
1148 return (e = getNode(key)) == null ? defaultValue : e.value;
1149 }
1150
1151 @Override
1152 public V putIfAbsent(K key, V value) {
1153 return putVal(hash(key), key, value, true, true);
1154 }
1155
1156 @Override
1157 public boolean remove(Object key, Object value) {
1158 return removeNode(hash(key), key, value, true, true) != null;
1159 }
1160
1161 @Override
1162 public boolean replace(K key, V oldValue, V newValue) {
1163 Node<K,V> e; V v;
1164 if ((e = getNode(key)) != null &&
1165 ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
1166 e.value = newValue;
1167 afterNodeAccess(e);
1168 return true;
1169 }
1170 return false;
1171 }
1172
1173 @Override
1174 public V replace(K key, V value) {
1175 Node<K,V> e;
1176 if ((e = getNode(key)) != null) {
1177 V oldValue = e.value;
1178 e.value = value;
1179 afterNodeAccess(e);
1180 return oldValue;
1181 }
1182 return null;
1183 }
1184
1185 /**
1186 * {@inheritDoc}
1187 *
1188 * <p>This method will, on a best-effort basis, throw a
1189 * {@link ConcurrentModificationException} if it is detected that the
1190 * mapping function modifies this map during computation.
1191 *
1192 * @throws ConcurrentModificationException if it is detected that the
1193 * mapping function modified this map
1194 */
1195 @Override
1196 public V computeIfAbsent(K key,
1197 Function<? super K, ? extends V> mappingFunction) {
1198 if (mappingFunction == null)
1199 throw new NullPointerException();
1200 int hash = hash(key);
1201 Node<K,V>[] tab; Node<K,V> first; int n, i;
1202 int binCount = 0;
1203 TreeNode<K,V> t = null;
1204 Node<K,V> old = null;
1205 if (size > threshold || (tab = table) == null ||
1206 (n = tab.length) == 0)
1207 n = (tab = resize()).length;
1208 if ((first = tab[i = (n - 1) & hash]) != null) {
1209 if (first instanceof TreeNode)
1210 old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
1211 else {
1212 Node<K,V> e = first; K k;
1213 do {
1214 if (e.hash == hash &&
1215 ((k = e.key) == key || (key != null && key.equals(k)))) {
1216 old = e;
1217 break;
1218 }
1219 ++binCount;
1220 } while ((e = e.next) != null);
1221 }
1222 V oldValue;
1223 if (old != null && (oldValue = old.value) != null) {
1224 afterNodeAccess(old);
1225 return oldValue;
1226 }
1227 }
1228 int mc = modCount;
1229 V v = mappingFunction.apply(key);
1230 if (mc != modCount) { throw new ConcurrentModificationException(); }
1231 if (v == null) {
1232 return null;
1233 } else if (old != null) {
1234 old.value = v;
1235 afterNodeAccess(old);
1236 return v;
1237 }
1238 else if (t != null)
1239 t.putTreeVal(this, tab, hash, key, v);
1240 else {
1241 tab[i] = newNode(hash, key, v, first);
1242 if (binCount >= TREEIFY_THRESHOLD - 1)
1243 treeifyBin(tab, hash);
1244 }
1245 modCount = mc + 1;
1246 ++size;
1247 afterNodeInsertion(true);
1248 return v;
1249 }
1250
1251 /**
1252 * {@inheritDoc}
1253 *
1254 * <p>This method will, on a best-effort basis, throw a
1255 * {@link ConcurrentModificationException} if it is detected that the
1256 * remapping function modifies this map during computation.
1257 *
1258 * @throws ConcurrentModificationException if it is detected that the
1259 * remapping function modified this map
1260 */
1261 @Override
1262 public V computeIfPresent(K key,
1263 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1264 if (remappingFunction == null)
1265 throw new NullPointerException();
1266 Node<K,V> e; V oldValue;
1267 if ((e = getNode(key)) != null &&
1268 (oldValue = e.value) != null) {
1269 int mc = modCount;
1270 V v = remappingFunction.apply(key, oldValue);
1271 if (mc != modCount) { throw new ConcurrentModificationException(); }
1272 if (v != null) {
1273 e.value = v;
1274 afterNodeAccess(e);
1275 return v;
1276 }
1277 else {
1278 int hash = hash(key);
1279 removeNode(hash, key, null, false, true);
1280 }
1281 }
1282 return null;
1283 }
1284
1285 /**
1286 * {@inheritDoc}
1287 *
1288 * <p>This method will, on a best-effort basis, throw a
1289 * {@link ConcurrentModificationException} if it is detected that the
1290 * remapping function modifies this map during computation.
1291 *
1292 * @throws ConcurrentModificationException if it is detected that the
1293 * remapping function modified this map
1294 */
1295 @Override
1296 public V compute(K key,
1297 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1298 if (remappingFunction == null)
1299 throw new NullPointerException();
1300 int hash = hash(key);
1301 Node<K,V>[] tab; Node<K,V> first; int n, i;
1302 int binCount = 0;
1303 TreeNode<K,V> t = null;
1304 Node<K,V> old = null;
1305 if (size > threshold || (tab = table) == null ||
1306 (n = tab.length) == 0)
1307 n = (tab = resize()).length;
1308 if ((first = tab[i = (n - 1) & hash]) != null) {
1309 if (first instanceof TreeNode)
1310 old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
1311 else {
1312 Node<K,V> e = first; K k;
1313 do {
1314 if (e.hash == hash &&
1315 ((k = e.key) == key || (key != null && key.equals(k)))) {
1316 old = e;
1317 break;
1318 }
1319 ++binCount;
1320 } while ((e = e.next) != null);
1321 }
1322 }
1323 V oldValue = (old == null) ? null : old.value;
1324 int mc = modCount;
1325 V v = remappingFunction.apply(key, oldValue);
1326 if (mc != modCount) { throw new ConcurrentModificationException(); }
1327 if (old != null) {
1328 if (v != null) {
1329 old.value = v;
1330 afterNodeAccess(old);
1331 }
1332 else
1333 removeNode(hash, key, null, false, true);
1334 }
1335 else if (v != null) {
1336 if (t != null)
1337 t.putTreeVal(this, tab, hash, key, v);
1338 else {
1339 tab[i] = newNode(hash, key, v, first);
1340 if (binCount >= TREEIFY_THRESHOLD - 1)
1341 treeifyBin(tab, hash);
1342 }
1343 modCount = mc + 1;
1344 ++size;
1345 afterNodeInsertion(true);
1346 }
1347 return v;
1348 }
1349
1350 /**
1351 * {@inheritDoc}
1352 *
1353 * <p>This method will, on a best-effort basis, throw a
1354 * {@link ConcurrentModificationException} if it is detected that the
1355 * remapping function modifies this map during computation.
1356 *
1357 * @throws ConcurrentModificationException if it is detected that the
1358 * remapping function modified this map
1359 */
1360 @Override
1361 public V merge(K key, V value,
1362 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1363 if (value == null || remappingFunction == null)
1364 throw new NullPointerException();
1365 int hash = hash(key);
1366 Node<K,V>[] tab; Node<K,V> first; int n, i;
1367 int binCount = 0;
1368 TreeNode<K,V> t = null;
1369 Node<K,V> old = null;
1370 if (size > threshold || (tab = table) == null ||
1371 (n = tab.length) == 0)
1372 n = (tab = resize()).length;
1373 if ((first = tab[i = (n - 1) & hash]) != null) {
1374 if (first instanceof TreeNode)
1375 old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
1376 else {
1377 Node<K,V> e = first; K k;
1378 do {
1379 if (e.hash == hash &&
1380 ((k = e.key) == key || (key != null && key.equals(k)))) {
1381 old = e;
1382 break;
1383 }
1384 ++binCount;
1385 } while ((e = e.next) != null);
1386 }
1387 }
1388 if (old != null) {
1389 V v;
1390 if (old.value != null) {
1391 int mc = modCount;
1392 v = remappingFunction.apply(old.value, value);
1393 if (mc != modCount) {
1394 throw new ConcurrentModificationException();
1395 }
1396 } else {
1397 v = value;
1398 }
1399 if (v != null) {
1400 old.value = v;
1401 afterNodeAccess(old);
1402 }
1403 else
1404 removeNode(hash, key, null, false, true);
1405 return v;
1406 } else {
1407 if (t != null)
1408 t.putTreeVal(this, tab, hash, key, value);
1409 else {
1410 tab[i] = newNode(hash, key, value, first);
1411 if (binCount >= TREEIFY_THRESHOLD - 1)
1412 treeifyBin(tab, hash);
1413 }
1414 ++modCount;
1415 ++size;
1416 afterNodeInsertion(true);
1417 return value;
1418 }
1419 }
1420
1421 @Override
1422 public void forEach(BiConsumer<? super K, ? super V> action) {
1423 Node<K,V>[] tab;
1424 if (action == null)
1425 throw new NullPointerException();
1426 if (size > 0 && (tab = table) != null) {
1427 int mc = modCount;
1428 for (Node<K,V> e : tab) {
1429 for (; e != null; e = e.next)
1430 action.accept(e.key, e.value);
1431 }
1432 if (modCount != mc)
1433 throw new ConcurrentModificationException();
1434 }
1435 }
1436
1437 @Override
1438 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1439 Node<K,V>[] tab;
1440 if (function == null)
1441 throw new NullPointerException();
1442 if (size > 0 && (tab = table) != null) {
1443 int mc = modCount;
1444 for (Node<K,V> e : tab) {
1445 for (; e != null; e = e.next) {
1446 e.value = function.apply(e.key, e.value);
1447 }
1448 }
1449 if (modCount != mc)
1450 throw new ConcurrentModificationException();
1451 }
1452 }
1453
1454 /* ------------------------------------------------------------ */
1455 // Cloning and serialization
1456
1457 /**
1458 * Returns a shallow copy of this {@code HashMap} instance: the keys and
1459 * values themselves are not cloned.
1460 *
1461 * @return a shallow copy of this map
1462 */
1463 @SuppressWarnings("unchecked")
1464 @Override
1465 public Object clone() {
1466 HashMap<K,V> result;
1467 try {
1468 result = (HashMap<K,V>)super.clone();
1469 } catch (CloneNotSupportedException e) {
1470 // this shouldn't happen, since we are Cloneable
1471 throw new InternalError(e);
1472 }
1473 result.reinitialize();
1474 result.putMapEntries(this, false);
1475 return result;
1476 }
1477
1478 // These methods are also used when serializing HashSets
1479 final float loadFactor() { return loadFactor; }
1480 final int capacity() {
1481 return (table != null) ? table.length :
1482 (threshold > 0) ? threshold :
1483 DEFAULT_INITIAL_CAPACITY;
1484 }
1485
1486 /**
1487 * Saves this map to a stream (that is, serializes it).
1488 *
1489 * @param s the stream
1490 * @throws IOException if an I/O error occurs
1491 * @serialData The <i>capacity</i> of the HashMap (the length of the
1492 * bucket array) is emitted (int), followed by the
1493 * <i>size</i> (an int, the number of key-value
1494 * mappings), followed by the key (Object) and value (Object)
1495 * for each key-value mapping. The key-value mappings are
1496 * emitted in no particular order.
1497 */
1498 @java.io.Serial
1499 private void writeObject(java.io.ObjectOutputStream s)
1500 throws IOException {
1501 int buckets = capacity();
1502 // Write out the threshold, loadfactor, and any hidden stuff
1503 s.defaultWriteObject();
1504 s.writeInt(buckets);
1505 s.writeInt(size);
1506 internalWriteEntries(s);
1507 }
1508
1509 /**
1510 * Reconstitutes this map from a stream (that is, deserializes it).
1511 * @param s the stream
1512 * @throws ClassNotFoundException if the class of a serialized object
1513 * could not be found
1514 * @throws IOException if an I/O error occurs
1515 */
1516 @java.io.Serial
1517 private void readObject(ObjectInputStream s)
1518 throws IOException, ClassNotFoundException {
1519
1520 ObjectInputStream.GetField fields = s.readFields();
1521
1522 // Read loadFactor (ignore threshold)
1523 float lf = fields.get("loadFactor", 0.75f);
1524 if (lf <= 0 || Float.isNaN(lf))
1525 throw new InvalidObjectException("Illegal load factor: " + lf);
1526
1527 lf = Math.clamp(lf, 0.25f, 4.0f);
1528 HashMap.UnsafeHolder.putLoadFactor(this, lf);
1529
1530 reinitialize();
1531
1532 s.readInt(); // Read and ignore number of buckets
1533 int mappings = s.readInt(); // Read number of mappings (size)
1534 if (mappings < 0) {
1535 throw new InvalidObjectException("Illegal mappings count: " + mappings);
1536 } else if (mappings == 0) {
1537 // use defaults
1538 } else if (mappings > 0) {
1539 double dc = Math.ceil(mappings / (double)lf);
1540 int cap = ((dc < DEFAULT_INITIAL_CAPACITY) ?
1541 DEFAULT_INITIAL_CAPACITY :
1542 (dc >= MAXIMUM_CAPACITY) ?
1543 MAXIMUM_CAPACITY :
1544 tableSizeFor((int)dc));
1545 float ft = (float)cap * lf;
1546 threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
1547 (int)ft : Integer.MAX_VALUE);
1548
1549 // Check Map.Entry[].class since it's the nearest public type to
1550 // what we're actually creating.
1551 SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Map.Entry[].class, cap);
1552 @SuppressWarnings({"rawtypes","unchecked"})
1553 Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
1554 table = tab;
1555
1556 // Read the keys and values, and put the mappings in the HashMap
1557 for (int i = 0; i < mappings; i++) {
1558 @SuppressWarnings("unchecked")
1559 K key = (K) s.readObject();
1560 @SuppressWarnings("unchecked")
1561 V value = (V) s.readObject();
1562 putVal(hash(key), key, value, false, false);
1563 }
1564 }
1565 }
1566
1567 // Support for resetting final field during deserializing
1568 private static final class UnsafeHolder {
1569 private UnsafeHolder() { throw new InternalError(); }
1570 private static final jdk.internal.misc.Unsafe unsafe
1571 = jdk.internal.misc.Unsafe.getUnsafe();
1572 private static final long LF_OFFSET
1573 = unsafe.objectFieldOffset(HashMap.class, "loadFactor");
1574 static void putLoadFactor(HashMap<?, ?> map, float lf) {
1575 unsafe.putFloat(map, LF_OFFSET, lf);
1576 }
1577 }
1578
1579 /* ------------------------------------------------------------ */
1580 // iterators
1581
1582 abstract class HashIterator {
1583 Node<K,V> next; // next entry to return
1584 Node<K,V> current; // current entry
1585 int expectedModCount; // for fast-fail
1586 int index; // current slot
1587
1588 HashIterator() {
1589 expectedModCount = modCount;
1590 Node<K,V>[] t = table;
1591 current = next = null;
1592 index = 0;
1593 if (t != null && size > 0) { // advance to first entry
1594 do {} while (index < t.length && (next = t[index++]) == null);
1595 }
1596 }
1597
1598 public final boolean hasNext() {
1599 return next != null;
1600 }
1601
1602 final Node<K,V> nextNode() {
1603 Node<K,V>[] t;
1604 Node<K,V> e = next;
1605 if (modCount != expectedModCount)
1606 throw new ConcurrentModificationException();
1607 if (e == null)
1608 throw new NoSuchElementException();
1609 if ((next = (current = e).next) == null && (t = table) != null) {
1610 do {} while (index < t.length && (next = t[index++]) == null);
1611 }
1612 return e;
1613 }
1614
1615 public final void remove() {
1616 Node<K,V> p = current;
1617 if (p == null)
1618 throw new IllegalStateException();
1619 if (modCount != expectedModCount)
1620 throw new ConcurrentModificationException();
1621 current = null;
1622 removeNode(p.hash, p.key, null, false, false);
1623 expectedModCount = modCount;
1624 }
1625 }
1626
1627 final class KeyIterator extends HashIterator
1628 implements Iterator<K> {
1629 public final K next() { return nextNode().key; }
1630 }
1631
1632 final class ValueIterator extends HashIterator
1633 implements Iterator<V> {
1634 public final V next() { return nextNode().value; }
1635 }
1636
1637 final class EntryIterator extends HashIterator
1638 implements Iterator<Map.Entry<K,V>> {
1639 public final Map.Entry<K,V> next() { return nextNode(); }
1640 }
1641
1642 /* ------------------------------------------------------------ */
1643 // spliterators
1644
1645 static class HashMapSpliterator<K,V> {
1646 final HashMap<K,V> map;
1647 Node<K,V> current; // current node
1648 int index; // current index, modified on advance/split
1649 int fence; // one past last index
1650 int est; // size estimate
1651 int expectedModCount; // for comodification checks
1652
1653 HashMapSpliterator(HashMap<K,V> m, int origin,
1654 int fence, int est,
1655 int expectedModCount) {
1656 this.map = m;
1657 this.index = origin;
1658 this.fence = fence;
1659 this.est = est;
1660 this.expectedModCount = expectedModCount;
1661 }
1662
1663 final int getFence() { // initialize fence and size on first use
1664 int hi;
1665 if ((hi = fence) < 0) {
1666 HashMap<K,V> m = map;
1667 est = m.size;
1668 expectedModCount = m.modCount;
1669 Node<K,V>[] tab = m.table;
1670 hi = fence = (tab == null) ? 0 : tab.length;
1671 }
1672 return hi;
1673 }
1674
1675 public final long estimateSize() {
1676 getFence(); // force init
1677 return (long) est;
1678 }
1679 }
1680
1681 static final class KeySpliterator<K,V>
1682 extends HashMapSpliterator<K,V>
1683 implements Spliterator<K> {
1684 KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,
1685 int expectedModCount) {
1686 super(m, origin, fence, est, expectedModCount);
1687 }
1688
1689 public KeySpliterator<K,V> trySplit() {
1690 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1691 return (lo >= mid || current != null) ? null :
1692 new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
1693 expectedModCount);
1694 }
1695
1696 public void forEachRemaining(Consumer<? super K> action) {
1697 int i, hi, mc;
1698 if (action == null)
1699 throw new NullPointerException();
1700 HashMap<K,V> m = map;
1701 Node<K,V>[] tab = m.table;
1702 if ((hi = fence) < 0) {
1703 mc = expectedModCount = m.modCount;
1704 hi = fence = (tab == null) ? 0 : tab.length;
1705 }
1706 else
1707 mc = expectedModCount;
1708 if (tab != null && tab.length >= hi &&
1709 (i = index) >= 0 && (i < (index = hi) || current != null)) {
1710 Node<K,V> p = current;
1711 current = null;
1712 do {
1713 if (p == null)
1714 p = tab[i++];
1715 else {
1716 action.accept(p.key);
1717 p = p.next;
1718 }
1719 } while (p != null || i < hi);
1720 if (m.modCount != mc)
1721 throw new ConcurrentModificationException();
1722 }
1723 }
1724
1725 public boolean tryAdvance(Consumer<? super K> action) {
1726 int hi;
1727 if (action == null)
1728 throw new NullPointerException();
1729 Node<K,V>[] tab = map.table;
1730 if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
1731 while (current != null || index < hi) {
1732 if (current == null)
1733 current = tab[index++];
1734 else {
1735 K k = current.key;
1736 current = current.next;
1737 action.accept(k);
1738 if (map.modCount != expectedModCount)
1739 throw new ConcurrentModificationException();
1740 return true;
1741 }
1742 }
1743 }
1744 return false;
1745 }
1746
1747 public int characteristics() {
1748 return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
1749 Spliterator.DISTINCT;
1750 }
1751 }
1752
1753 static final class ValueSpliterator<K,V>
1754 extends HashMapSpliterator<K,V>
1755 implements Spliterator<V> {
1756 ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,
1757 int expectedModCount) {
1758 super(m, origin, fence, est, expectedModCount);
1759 }
1760
1761 public ValueSpliterator<K,V> trySplit() {
1762 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1763 return (lo >= mid || current != null) ? null :
1764 new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
1765 expectedModCount);
1766 }
1767
1768 public void forEachRemaining(Consumer<? super V> action) {
1769 int i, hi, mc;
1770 if (action == null)
1771 throw new NullPointerException();
1772 HashMap<K,V> m = map;
1773 Node<K,V>[] tab = m.table;
1774 if ((hi = fence) < 0) {
1775 mc = expectedModCount = m.modCount;
1776 hi = fence = (tab == null) ? 0 : tab.length;
1777 }
1778 else
1779 mc = expectedModCount;
1780 if (tab != null && tab.length >= hi &&
1781 (i = index) >= 0 && (i < (index = hi) || current != null)) {
1782 Node<K,V> p = current;
1783 current = null;
1784 do {
1785 if (p == null)
1786 p = tab[i++];
1787 else {
1788 action.accept(p.value);
1789 p = p.next;
1790 }
1791 } while (p != null || i < hi);
1792 if (m.modCount != mc)
1793 throw new ConcurrentModificationException();
1794 }
1795 }
1796
1797 public boolean tryAdvance(Consumer<? super V> action) {
1798 int hi;
1799 if (action == null)
1800 throw new NullPointerException();
1801 Node<K,V>[] tab = map.table;
1802 if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
1803 while (current != null || index < hi) {
1804 if (current == null)
1805 current = tab[index++];
1806 else {
1807 V v = current.value;
1808 current = current.next;
1809 action.accept(v);
1810 if (map.modCount != expectedModCount)
1811 throw new ConcurrentModificationException();
1812 return true;
1813 }
1814 }
1815 }
1816 return false;
1817 }
1818
1819 public int characteristics() {
1820 return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
1821 }
1822 }
1823
1824 static final class EntrySpliterator<K,V>
1825 extends HashMapSpliterator<K,V>
1826 implements Spliterator<Map.Entry<K,V>> {
1827 EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,
1828 int expectedModCount) {
1829 super(m, origin, fence, est, expectedModCount);
1830 }
1831
1832 public EntrySpliterator<K,V> trySplit() {
1833 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1834 return (lo >= mid || current != null) ? null :
1835 new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
1836 expectedModCount);
1837 }
1838
1839 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
1840 int i, hi, mc;
1841 if (action == null)
1842 throw new NullPointerException();
1843 HashMap<K,V> m = map;
1844 Node<K,V>[] tab = m.table;
1845 if ((hi = fence) < 0) {
1846 mc = expectedModCount = m.modCount;
1847 hi = fence = (tab == null) ? 0 : tab.length;
1848 }
1849 else
1850 mc = expectedModCount;
1851 if (tab != null && tab.length >= hi &&
1852 (i = index) >= 0 && (i < (index = hi) || current != null)) {
1853 Node<K,V> p = current;
1854 current = null;
1855 do {
1856 if (p == null)
1857 p = tab[i++];
1858 else {
1859 action.accept(p);
1860 p = p.next;
1861 }
1862 } while (p != null || i < hi);
1863 if (m.modCount != mc)
1864 throw new ConcurrentModificationException();
1865 }
1866 }
1867
1868 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
1869 int hi;
1870 if (action == null)
1871 throw new NullPointerException();
1872 Node<K,V>[] tab = map.table;
1873 if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
1874 while (current != null || index < hi) {
1875 if (current == null)
1876 current = tab[index++];
1877 else {
1878 Node<K,V> e = current;
1879 current = current.next;
1880 action.accept(e);
1881 if (map.modCount != expectedModCount)
1882 throw new ConcurrentModificationException();
1883 return true;
1884 }
1885 }
1886 }
1887 return false;
1888 }
1889
1890 public int characteristics() {
1891 return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
1892 Spliterator.DISTINCT;
1893 }
1894 }
1895
1896 /* ------------------------------------------------------------ */
1897 // LinkedHashMap support
1898
1899
1900 /*
1901 * The following package-protected methods are designed to be
1902 * overridden by LinkedHashMap, but not by any other subclass.
1903 * Nearly all other internal methods are also package-protected
1904 * but are declared final, so can be used by LinkedHashMap, view
1905 * classes, and HashSet.
1906 */
1907
1908 // Create a regular (non-tree) node
1909 Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
1910 return new Node<>(hash, key, value, next);
1911 }
1912
1913 // For conversion from TreeNodes to plain nodes
1914 Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
1915 return new Node<>(p.hash, p.key, p.value, next);
1916 }
1917
1918 // Create a tree bin node
1919 TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
1920 return new TreeNode<>(hash, key, value, next);
1921 }
1922
1923 // For treeifyBin
1924 TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
1925 return new TreeNode<>(p.hash, p.key, p.value, next);
1926 }
1927
1928 /**
1929 * Reset to initial default state. Called by clone and readObject.
1930 */
1931 void reinitialize() {
1932 table = null;
1933 entrySet = null;
1934 keySet = null;
1935 values = null;
1936 modCount = 0;
1937 threshold = 0;
1938 size = 0;
1939 }
1940
1941 // Callbacks to allow LinkedHashMap post-actions
1942 void afterNodeAccess(Node<K,V> p) { }
1943 void afterNodeInsertion(boolean evict) { }
1944 void afterNodeRemoval(Node<K,V> p) { }
1945
1946 // Called only from writeObject, to ensure compatible ordering.
1947 void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
1948 Node<K,V>[] tab;
1949 if (size > 0 && (tab = table) != null) {
1950 for (Node<K,V> e : tab) {
1951 for (; e != null; e = e.next) {
1952 s.writeObject(e.key);
1953 s.writeObject(e.value);
1954 }
1955 }
1956 }
1957 }
1958
1959 /* ------------------------------------------------------------ */
1960 // Tree bins
1961
1962 /**
1963 * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
1964 * extends Node) so can be used as extension of either regular or
1965 * linked node.
1966 */
1967 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
1968 TreeNode<K,V> parent; // red-black tree links
1969 TreeNode<K,V> left;
1970 TreeNode<K,V> right;
1971 TreeNode<K,V> prev; // needed to unlink next upon deletion
1972 boolean red;
1973 TreeNode(int hash, K key, V val, Node<K,V> next) {
1974 super(hash, key, val, next);
1975 }
1976
1977 /**
1978 * Returns root of tree containing this node.
1979 */
1980 final TreeNode<K,V> root() {
1981 for (TreeNode<K,V> r = this, p;;) {
1982 if ((p = r.parent) == null)
1983 return r;
1984 r = p;
1985 }
1986 }
1987
1988 /**
1989 * Ensures that the given root is the first node of its bin.
1990 */
1991 static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
1992 int n;
1993 if (root != null && tab != null && (n = tab.length) > 0) {
1994 int index = (n - 1) & root.hash;
1995 TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
1996 if (root != first) {
1997 Node<K,V> rn;
1998 tab[index] = root;
1999 TreeNode<K,V> rp = root.prev;
2000 if ((rn = root.next) != null)
2001 ((TreeNode<K,V>)rn).prev = rp;
2002 if (rp != null)
2003 rp.next = rn;
2004 if (first != null)
2005 first.prev = root;
2006 root.next = first;
2007 root.prev = null;
2008 }
2009 assert checkInvariants(root);
2010 }
2011 }
2012
2013 /**
2014 * Finds the node starting at root p with the given hash and key.
2015 * The kc argument caches comparableClassFor(key) upon first use
2016 * comparing keys.
2017 */
2018 final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
2019 TreeNode<K,V> p = this;
2020 do {
2021 int ph, dir; K pk;
2022 TreeNode<K,V> pl = p.left, pr = p.right, q;
2023 if ((ph = p.hash) > h)
2024 p = pl;
2025 else if (ph < h)
2026 p = pr;
2027 else if ((pk = p.key) == k || (k != null && k.equals(pk)))
2028 return p;
2029 else if (pl == null)
2030 p = pr;
2031 else if (pr == null)
2032 p = pl;
2033 else if ((kc != null ||
2034 (kc = comparableClassFor(k)) != null) &&
2035 (dir = compareComparables(kc, k, pk)) != 0)
2036 p = (dir < 0) ? pl : pr;
2037 else if ((q = pr.find(h, k, kc)) != null)
2038 return q;
2039 else
2040 p = pl;
2041 } while (p != null);
2042 return null;
2043 }
2044
2045 /**
2046 * Calls find for root node.
2047 */
2048 final TreeNode<K,V> getTreeNode(int h, Object k) {
2049 return ((parent != null) ? root() : this).find(h, k, null);
2050 }
2051
2052 /**
2053 * Tie-breaking utility for ordering insertions when equal
2054 * hashCodes and non-comparable. We don't require a total
2055 * order, just a consistent insertion rule to maintain
2056 * equivalence across rebalancings. Tie-breaking further than
2057 * necessary simplifies testing a bit.
2058 */
2059 static int tieBreakOrder(Object a, Object b) {
2060 int d;
2061 if (a == null || b == null ||
2062 (d = a.getClass().getName().
2063 compareTo(b.getClass().getName())) == 0)
2064 d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2065 -1 : 1);
2066 return d;
2067 }
2068
2069 /**
2070 * Forms tree of the nodes linked from this node.
2071 */
2072 final void treeify(Node<K,V>[] tab) {
2073 TreeNode<K,V> root = null;
2074 for (TreeNode<K,V> x = this, next; x != null; x = next) {
2075 next = (TreeNode<K,V>)x.next;
2076 x.left = x.right = null;
2077 if (root == null) {
2078 x.parent = null;
2079 x.red = false;
2080 root = x;
2081 }
2082 else {
2083 K k = x.key;
2084 int h = x.hash;
2085 Class<?> kc = null;
2086 for (TreeNode<K,V> p = root;;) {
2087 int dir, ph;
2088 K pk = p.key;
2089 if ((ph = p.hash) > h)
2090 dir = -1;
2091 else if (ph < h)
2092 dir = 1;
2093 else if ((kc == null &&
2094 (kc = comparableClassFor(k)) == null) ||
2095 (dir = compareComparables(kc, k, pk)) == 0)
2096 dir = tieBreakOrder(k, pk);
2097
2098 TreeNode<K,V> xp = p;
2099 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2100 x.parent = xp;
2101 if (dir <= 0)
2102 xp.left = x;
2103 else
2104 xp.right = x;
2105 root = balanceInsertion(root, x);
2106 break;
2107 }
2108 }
2109 }
2110 }
2111 moveRootToFront(tab, root);
2112 }
2113
2114 /**
2115 * Returns a list of non-TreeNodes replacing those linked from
2116 * this node.
2117 */
2118 final Node<K,V> untreeify(HashMap<K,V> map) {
2119 Node<K,V> hd = null, tl = null;
2120 for (Node<K,V> q = this; q != null; q = q.next) {
2121 Node<K,V> p = map.replacementNode(q, null);
2122 if (tl == null)
2123 hd = p;
2124 else
2125 tl.next = p;
2126 tl = p;
2127 }
2128 return hd;
2129 }
2130
2131 /**
2132 * Tree version of putVal.
2133 */
2134 final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
2135 int h, K k, V v) {
2136 Class<?> kc = null;
2137 boolean searched = false;
2138 TreeNode<K,V> root = (parent != null) ? root() : this;
2139 for (TreeNode<K,V> p = root;;) {
2140 int dir, ph; K pk;
2141 if ((ph = p.hash) > h)
2142 dir = -1;
2143 else if (ph < h)
2144 dir = 1;
2145 else if ((pk = p.key) == k || (k != null && k.equals(pk)))
2146 return p;
2147 else if ((kc == null &&
2148 (kc = comparableClassFor(k)) == null) ||
2149 (dir = compareComparables(kc, k, pk)) == 0) {
2150 if (!searched) {
2151 TreeNode<K,V> q, ch;
2152 searched = true;
2153 if (((ch = p.left) != null &&
2154 (q = ch.find(h, k, kc)) != null) ||
2155 ((ch = p.right) != null &&
2156 (q = ch.find(h, k, kc)) != null))
2157 return q;
2158 }
2159 dir = tieBreakOrder(k, pk);
2160 }
2161
2162 TreeNode<K,V> xp = p;
2163 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2164 Node<K,V> xpn = xp.next;
2165 TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
2166 if (dir <= 0)
2167 xp.left = x;
2168 else
2169 xp.right = x;
2170 xp.next = x;
2171 x.parent = x.prev = xp;
2172 if (xpn != null)
2173 ((TreeNode<K,V>)xpn).prev = x;
2174 moveRootToFront(tab, balanceInsertion(root, x));
2175 return null;
2176 }
2177 }
2178 }
2179
2180 /**
2181 * Removes the given node, that must be present before this call.
2182 * This is messier than typical red-black deletion code because we
2183 * cannot swap the contents of an interior node with a leaf
2184 * successor that is pinned by "next" pointers that are accessible
2185 * independently during traversal. So instead we swap the tree
2186 * linkages. If the current tree appears to have too few nodes,
2187 * the bin is converted back to a plain bin. (The test triggers
2188 * somewhere between 2 and 6 nodes, depending on tree structure).
2189 */
2190 final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
2191 boolean movable) {
2192 int n;
2193 if (tab == null || (n = tab.length) == 0)
2194 return;
2195 int index = (n - 1) & hash;
2196 TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
2197 TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
2198 if (pred == null)
2199 tab[index] = first = succ;
2200 else
2201 pred.next = succ;
2202 if (succ != null)
2203 succ.prev = pred;
2204 if (first == null)
2205 return;
2206 if (root.parent != null)
2207 root = root.root();
2208 if (root == null
2209 || (movable
2210 && (root.right == null
2211 || (rl = root.left) == null
2212 || rl.left == null))) {
2213 tab[index] = first.untreeify(map); // too small
2214 return;
2215 }
2216 TreeNode<K,V> p = this, pl = left, pr = right, replacement;
2217 if (pl != null && pr != null) {
2218 TreeNode<K,V> s = pr, sl;
2219 while ((sl = s.left) != null) // find successor
2220 s = sl;
2221 boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2222 TreeNode<K,V> sr = s.right;
2223 TreeNode<K,V> pp = p.parent;
2224 if (s == pr) { // p was s's direct parent
2225 p.parent = s;
2226 s.right = p;
2227 }
2228 else {
2229 TreeNode<K,V> sp = s.parent;
2230 if ((p.parent = sp) != null) {
2231 if (s == sp.left)
2232 sp.left = p;
2233 else
2234 sp.right = p;
2235 }
2236 if ((s.right = pr) != null)
2237 pr.parent = s;
2238 }
2239 p.left = null;
2240 if ((p.right = sr) != null)
2241 sr.parent = p;
2242 if ((s.left = pl) != null)
2243 pl.parent = s;
2244 if ((s.parent = pp) == null)
2245 root = s;
2246 else if (p == pp.left)
2247 pp.left = s;
2248 else
2249 pp.right = s;
2250 if (sr != null)
2251 replacement = sr;
2252 else
2253 replacement = p;
2254 }
2255 else if (pl != null)
2256 replacement = pl;
2257 else if (pr != null)
2258 replacement = pr;
2259 else
2260 replacement = p;
2261 if (replacement != p) {
2262 TreeNode<K,V> pp = replacement.parent = p.parent;
2263 if (pp == null)
2264 (root = replacement).red = false;
2265 else if (p == pp.left)
2266 pp.left = replacement;
2267 else
2268 pp.right = replacement;
2269 p.left = p.right = p.parent = null;
2270 }
2271
2272 TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
2273
2274 if (replacement == p) { // detach
2275 TreeNode<K,V> pp = p.parent;
2276 p.parent = null;
2277 if (pp != null) {
2278 if (p == pp.left)
2279 pp.left = null;
2280 else if (p == pp.right)
2281 pp.right = null;
2282 }
2283 }
2284 if (movable)
2285 moveRootToFront(tab, r);
2286 }
2287
2288 /**
2289 * Splits nodes in a tree bin into lower and upper tree bins,
2290 * or untreeifies if now too small. Called only from resize;
2291 * see above discussion about split bits and indices.
2292 *
2293 * @param map the map
2294 * @param tab the table for recording bin heads
2295 * @param index the index of the table being split
2296 * @param bit the bit of hash to split on
2297 */
2298 final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
2299 TreeNode<K,V> b = this;
2300 // Relink into lo and hi lists, preserving order
2301 TreeNode<K,V> loHead = null, loTail = null;
2302 TreeNode<K,V> hiHead = null, hiTail = null;
2303 int lc = 0, hc = 0;
2304 for (TreeNode<K,V> e = b, next; e != null; e = next) {
2305 next = (TreeNode<K,V>)e.next;
2306 e.next = null;
2307 if ((e.hash & bit) == 0) {
2308 if ((e.prev = loTail) == null)
2309 loHead = e;
2310 else
2311 loTail.next = e;
2312 loTail = e;
2313 ++lc;
2314 }
2315 else {
2316 if ((e.prev = hiTail) == null)
2317 hiHead = e;
2318 else
2319 hiTail.next = e;
2320 hiTail = e;
2321 ++hc;
2322 }
2323 }
2324
2325 if (loHead != null) {
2326 if (lc <= UNTREEIFY_THRESHOLD)
2327 tab[index] = loHead.untreeify(map);
2328 else {
2329 tab[index] = loHead;
2330 if (hiHead != null) // (else is already treeified)
2331 loHead.treeify(tab);
2332 }
2333 }
2334 if (hiHead != null) {
2335 if (hc <= UNTREEIFY_THRESHOLD)
2336 tab[index + bit] = hiHead.untreeify(map);
2337 else {
2338 tab[index + bit] = hiHead;
2339 if (loHead != null)
2340 hiHead.treeify(tab);
2341 }
2342 }
2343 }
2344
2345 /* ------------------------------------------------------------ */
2346 // Red-black tree methods, all adapted from CLR
2347
2348 static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2349 TreeNode<K,V> p) {
2350 TreeNode<K,V> r, pp, rl;
2351 if (p != null && (r = p.right) != null) {
2352 if ((rl = p.right = r.left) != null)
2353 rl.parent = p;
2354 if ((pp = r.parent = p.parent) == null)
2355 (root = r).red = false;
2356 else if (pp.left == p)
2357 pp.left = r;
2358 else
2359 pp.right = r;
2360 r.left = p;
2361 p.parent = r;
2362 }
2363 return root;
2364 }
2365
2366 static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2367 TreeNode<K,V> p) {
2368 TreeNode<K,V> l, pp, lr;
2369 if (p != null && (l = p.left) != null) {
2370 if ((lr = p.left = l.right) != null)
2371 lr.parent = p;
2372 if ((pp = l.parent = p.parent) == null)
2373 (root = l).red = false;
2374 else if (pp.right == p)
2375 pp.right = l;
2376 else
2377 pp.left = l;
2378 l.right = p;
2379 p.parent = l;
2380 }
2381 return root;
2382 }
2383
2384 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2385 TreeNode<K,V> x) {
2386 x.red = true;
2387 for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2388 if ((xp = x.parent) == null) {
2389 x.red = false;
2390 return x;
2391 }
2392 else if (!xp.red || (xpp = xp.parent) == null)
2393 return root;
2394 if (xp == (xppl = xpp.left)) {
2395 if ((xppr = xpp.right) != null && xppr.red) {
2396 xppr.red = false;
2397 xp.red = false;
2398 xpp.red = true;
2399 x = xpp;
2400 }
2401 else {
2402 if (x == xp.right) {
2403 root = rotateLeft(root, x = xp);
2404 xpp = (xp = x.parent) == null ? null : xp.parent;
2405 }
2406 if (xp != null) {
2407 xp.red = false;
2408 if (xpp != null) {
2409 xpp.red = true;
2410 root = rotateRight(root, xpp);
2411 }
2412 }
2413 }
2414 }
2415 else {
2416 if (xppl != null && xppl.red) {
2417 xppl.red = false;
2418 xp.red = false;
2419 xpp.red = true;
2420 x = xpp;
2421 }
2422 else {
2423 if (x == xp.left) {
2424 root = rotateRight(root, x = xp);
2425 xpp = (xp = x.parent) == null ? null : xp.parent;
2426 }
2427 if (xp != null) {
2428 xp.red = false;
2429 if (xpp != null) {
2430 xpp.red = true;
2431 root = rotateLeft(root, xpp);
2432 }
2433 }
2434 }
2435 }
2436 }
2437 }
2438
2439 static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2440 TreeNode<K,V> x) {
2441 for (TreeNode<K,V> xp, xpl, xpr;;) {
2442 if (x == null || x == root)
2443 return root;
2444 else if ((xp = x.parent) == null) {
2445 x.red = false;
2446 return x;
2447 }
2448 else if (x.red) {
2449 x.red = false;
2450 return root;
2451 }
2452 else if ((xpl = xp.left) == x) {
2453 if ((xpr = xp.right) != null && xpr.red) {
2454 xpr.red = false;
2455 xp.red = true;
2456 root = rotateLeft(root, xp);
2457 xpr = (xp = x.parent) == null ? null : xp.right;
2458 }
2459 if (xpr == null)
2460 x = xp;
2461 else {
2462 TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2463 if ((sr == null || !sr.red) &&
2464 (sl == null || !sl.red)) {
2465 xpr.red = true;
2466 x = xp;
2467 }
2468 else {
2469 if (sr == null || !sr.red) {
2470 if (sl != null)
2471 sl.red = false;
2472 xpr.red = true;
2473 root = rotateRight(root, xpr);
2474 xpr = (xp = x.parent) == null ?
2475 null : xp.right;
2476 }
2477 if (xpr != null) {
2478 xpr.red = (xp == null) ? false : xp.red;
2479 if ((sr = xpr.right) != null)
2480 sr.red = false;
2481 }
2482 if (xp != null) {
2483 xp.red = false;
2484 root = rotateLeft(root, xp);
2485 }
2486 x = root;
2487 }
2488 }
2489 }
2490 else { // symmetric
2491 if (xpl != null && xpl.red) {
2492 xpl.red = false;
2493 xp.red = true;
2494 root = rotateRight(root, xp);
2495 xpl = (xp = x.parent) == null ? null : xp.left;
2496 }
2497 if (xpl == null)
2498 x = xp;
2499 else {
2500 TreeNode<K,V> sl = xpl.left, sr = xpl.right;
2501 if ((sl == null || !sl.red) &&
2502 (sr == null || !sr.red)) {
2503 xpl.red = true;
2504 x = xp;
2505 }
2506 else {
2507 if (sl == null || !sl.red) {
2508 if (sr != null)
2509 sr.red = false;
2510 xpl.red = true;
2511 root = rotateLeft(root, xpl);
2512 xpl = (xp = x.parent) == null ?
2513 null : xp.left;
2514 }
2515 if (xpl != null) {
2516 xpl.red = (xp == null) ? false : xp.red;
2517 if ((sl = xpl.left) != null)
2518 sl.red = false;
2519 }
2520 if (xp != null) {
2521 xp.red = false;
2522 root = rotateRight(root, xp);
2523 }
2524 x = root;
2525 }
2526 }
2527 }
2528 }
2529 }
2530
2531 /**
2532 * Recursive invariant check
2533 */
2534 static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
2535 TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
2536 tb = t.prev, tn = (TreeNode<K,V>)t.next;
2537 if (tb != null && tb.next != t)
2538 return false;
2539 if (tn != null && tn.prev != t)
2540 return false;
2541 if (tp != null && t != tp.left && t != tp.right)
2542 return false;
2543 if (tl != null && (tl.parent != t || tl.hash > t.hash))
2544 return false;
2545 if (tr != null && (tr.parent != t || tr.hash < t.hash))
2546 return false;
2547 if (t.red && tl != null && tl.red && tr != null && tr.red)
2548 return false;
2549 if (tl != null && !checkInvariants(tl))
2550 return false;
2551 if (tr != null && !checkInvariants(tr))
2552 return false;
2553 return true;
2554 }
2555 }
2556
2557 /**
2558 * Calculate initial capacity for HashMap based classes, from expected size and default load factor (0.75).
2559 *
2560 * @param numMappings the expected number of mappings
2561 * @return initial capacity for HashMap based classes.
2562 * @since 19
2563 */
2564 static int calculateHashMapCapacity(int numMappings) {
2565 return (int) Math.ceil(numMappings / (double) DEFAULT_LOAD_FACTOR);
2566 }
2567
2568 /**
2569 * Creates a new, empty HashMap suitable for the expected number of mappings.
2570 * The returned map uses the default load factor of 0.75, and its initial capacity is
2571 * generally large enough so that the expected number of mappings can be added
2572 * without resizing the map.
2573 *
2574 * @param numMappings the expected number of mappings
2575 * @param <K> the type of keys maintained by the new map
2576 * @param <V> the type of mapped values
2577 * @return the newly created map
2578 * @throws IllegalArgumentException if numMappings is negative
2579 * @since 19
2580 */
2581 public static <K, V> HashMap<K, V> newHashMap(int numMappings) {
2582 if (numMappings < 0) {
2583 throw new IllegalArgumentException("Negative number of mappings: " + numMappings);
2584 }
2585 return new HashMap<>(calculateHashMapCapacity(numMappings));
2586 }
2587
2588 }