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