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