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