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