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