1 /*
   2  * Copyright (c) 1997, 2010, 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 import java.io.*;
  28 
  29 /**
  30  * Hash table based implementation of the <tt>Map</tt> interface.  This
  31  * implementation provides all of the optional map operations, and permits
  32  * <tt>null</tt> values and the <tt>null</tt> key.  (The <tt>HashMap</tt>
  33  * class is roughly equivalent to <tt>Hashtable</tt>, except that it is
  34  * unsynchronized and permits nulls.)  This class makes no guarantees as to
  35  * the order of the map; in particular, it does not guarantee that the order
  36  * will remain constant over time.
  37  *
  38  * <p>This implementation provides constant-time performance for the basic
  39  * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
  40  * disperses the elements properly among the buckets.  Iteration over
  41  * collection views requires time proportional to the "capacity" of the
  42  * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
  43  * of key-value mappings).  Thus, it's very important not to set the initial
  44  * capacity too high (or the load factor too low) if iteration performance is
  45  * important.
  46  *
  47  * <p>An instance of <tt>HashMap</tt> has two parameters that affect its
  48  * performance: <i>initial capacity</i> and <i>load factor</i>.  The
  49  * <i>capacity</i> is the number of buckets in the hash table, and the initial
  50  * capacity is simply the capacity at the time the hash table is created.  The
  51  * <i>load factor</i> is a measure of how full the hash table is allowed to
  52  * get before its capacity is automatically increased.  When the number of
  53  * entries in the hash table exceeds the product of the load factor and the
  54  * current capacity, the hash table is <i>rehashed</i> (that is, internal data
  55  * structures are rebuilt) so that the hash table has approximately twice the
  56  * number of buckets.
  57  *
  58  * <p>As a general rule, the default load factor (.75) offers a good tradeoff
  59  * between time and space costs.  Higher values decrease the space overhead
  60  * but increase the lookup cost (reflected in most of the operations of the
  61  * <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>).  The
  62  * expected number of entries in the map and its load factor should be taken
  63  * into account when setting its initial capacity, so as to minimize the
  64  * number of rehash operations.  If the initial capacity is greater
  65  * than the maximum number of entries divided by the load factor, no
  66  * rehash operations will ever occur.
  67  *
  68  * <p>If many mappings are to be stored in a <tt>HashMap</tt> instance,
  69  * creating it with a sufficiently large capacity will allow the mappings to
  70  * be stored more efficiently than letting it perform automatic rehashing as
  71  * needed to grow the table.
  72  *
  73  * <p><strong>Note that this implementation is not synchronized.</strong>
  74  * If multiple threads access a hash map concurrently, and at least one of
  75  * the threads modifies the map structurally, it <i>must</i> be
  76  * synchronized externally.  (A structural modification is any operation
  77  * that adds or deletes one or more mappings; merely changing the value
  78  * associated with a key that an instance already contains is not a
  79  * structural modification.)  This is typically accomplished by
  80  * synchronizing on some object that naturally encapsulates the map.
  81  *
  82  * If no such object exists, the map should be "wrapped" using the
  83  * {@link Collections#synchronizedMap Collections.synchronizedMap}
  84  * method.  This is best done at creation time, to prevent accidental
  85  * unsynchronized access to the map:<pre>
  86  *   Map m = Collections.synchronizedMap(new HashMap(...));</pre>
  87  *
  88  * <p>The iterators returned by all of this class's "collection view methods"
  89  * are <i>fail-fast</i>: if the map is structurally modified at any time after
  90  * the iterator is created, in any way except through the iterator's own
  91  * <tt>remove</tt> method, the iterator will throw a
  92  * {@link ConcurrentModificationException}.  Thus, in the face of concurrent
  93  * modification, the iterator fails quickly and cleanly, rather than risking
  94  * arbitrary, non-deterministic behavior at an undetermined time in the
  95  * future.
  96  *
  97  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  98  * as it is, generally speaking, impossible to make any hard guarantees in the
  99  * presence of unsynchronized concurrent modification.  Fail-fast iterators
 100  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 101  * Therefore, it would be wrong to write a program that depended on this
 102  * exception for its correctness: <i>the fail-fast behavior of iterators
 103  * should be used only to detect bugs.</i>
 104  *
 105  * <p>This class is a member of the
 106  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 107  * Java Collections Framework</a>.
 108  *
 109  * @param <K> the type of keys maintained by this map
 110  * @param <V> the type of mapped values
 111  *
 112  * @author  Doug Lea
 113  * @author  Josh Bloch
 114  * @author  Arthur van Hoff
 115  * @author  Neal Gafter
 116  * @see     Object#hashCode()
 117  * @see     Collection
 118  * @see     Map
 119  * @see     TreeMap
 120  * @see     Hashtable
 121  * @since   1.2
 122  */
 123 
 124 public class HashMap<K,V>
 125     extends AbstractMap<K,V>
 126     implements Map<K,V>, Cloneable, Serializable
 127 {
 128 
 129     /**
 130      * The default initial capacity - MUST be a power of two.
 131      */
 132     static final int DEFAULT_INITIAL_CAPACITY = 16;
 133 
 134     /**
 135      * The maximum capacity, used if a higher value is implicitly specified
 136      * by either of the constructors with arguments.
 137      * MUST be a power of two <= 1<<30.
 138      */
 139     static final int MAXIMUM_CAPACITY = 1 << 30;
 140 
 141     /**
 142      * The load factor used when none specified in constructor.
 143      */
 144     static final float DEFAULT_LOAD_FACTOR = 0.75f;
 145 
 146     /**
 147      * The table, resized as necessary. Length MUST Always be a power of two.
 148      */
 149     transient Entry<K,V>[] table;
 150 
 151     /**
 152      * The number of key-value mappings contained in this map.
 153      */
 154     transient int size;
 155 
 156     /**
 157      * The next size value at which to resize (capacity * load factor).
 158      * @serial
 159      */
 160     int threshold;
 161 
 162     /**
 163      * The load factor for the hash table.
 164      *
 165      * @serial
 166      */
 167     final float loadFactor;
 168 
 169     /**
 170      * The number of times this HashMap has been structurally modified
 171      * Structural modifications are those that change the number of mappings in
 172      * the HashMap or otherwise modify its internal structure (e.g.,
 173      * rehash).  This field is used to make iterators on Collection-views of
 174      * the HashMap fail-fast.  (See ConcurrentModificationException).
 175      */
 176     transient int modCount;
 177 
 178     /**
 179      * The default threshold of map capacity above which alternative hashing is
 180      * used for String keys. Alternative hashing reduces the incidence of
 181      * collisions due to weak hash code calculation for String keys.
 182      * <p/>
 183      * This value may be overridden by defining the system property
 184      * {@code jdk.map.althashing.threshold}. A property value of {@code 1}
 185      * forces alternative hashing to be used at all times whereas
 186      * {@code -1} value ensures that alternative hashing is never used.
 187      */
 188     static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
 189 
 190     /**
 191      * holds values which can't be initialized until after VM is booted.
 192      */
 193     private static class Holder {
 194 
 195             // Unsafe mechanics
 196         /**
 197          * Unsafe utilities
 198          */
 199         static final sun.misc.Unsafe UNSAFE;
 200 
 201         /**
 202          * Offset of "final" hashSeed field we must set in readObject() method.
 203          */
 204         static final long HASHSEED_OFFSET;
 205 
 206         /**
 207          * Table capacity above which to switch to use alternative hashing.
 208          */
 209         static final int ALTERNATIVE_HASHING_THRESHOLD;
 210 
 211         static {
 212             String altThreshold = java.security.AccessController.doPrivileged(
 213                 new sun.security.action.GetPropertyAction(
 214                     "jdk.map.althashing.threshold"));
 215 
 216             int threshold;
 217             try {
 218                 threshold = (null != altThreshold)
 219                         ? Integer.parseInt(altThreshold)
 220                         : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
 221 
 222                 // disable alternative hashing if -1
 223                 if (threshold == -1) {
 224                     threshold = Integer.MAX_VALUE;
 225                 }
 226 
 227                 if (threshold < 0) {
 228                     throw new IllegalArgumentException("value must be positive integer.");
 229                 }
 230             } catch(IllegalArgumentException failed) {
 231                 throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
 232             }
 233             ALTERNATIVE_HASHING_THRESHOLD = threshold;
 234 
 235             try {
 236                 UNSAFE = sun.misc.Unsafe.getUnsafe();
 237                 HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
 238                     HashMap.class.getDeclaredField("hashSeed"));
 239             } catch (NoSuchFieldException | SecurityException e) {
 240                 throw new Error("Failed to record hashSeed offset", e);
 241             }
 242         }
 243     }
 244 
 245     /**
 246      * If {@code true} then perform alternative hashing of String keys to reduce
 247      * the incidence of collisions due to weak hash code calculation.
 248      */
 249     transient boolean useAltHashing;
 250 
 251     /**
 252      * A randomizing value associated with this instance that is applied to
 253      * hash code of keys to make hash collisions harder to find.
 254      */
 255     transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
 256 
 257     /**
 258      * Constructs an empty <tt>HashMap</tt> with the specified initial
 259      * capacity and load factor.
 260      *
 261      * @param  initialCapacity the initial capacity
 262      * @param  loadFactor      the load factor
 263      * @throws IllegalArgumentException if the initial capacity is negative
 264      *         or the load factor is nonpositive
 265      */
 266     public HashMap(int initialCapacity, float loadFactor) {
 267         if (initialCapacity < 0)
 268             throw new IllegalArgumentException("Illegal initial capacity: " +
 269                                                initialCapacity);
 270         if (initialCapacity > MAXIMUM_CAPACITY)
 271             initialCapacity = MAXIMUM_CAPACITY;
 272         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 273             throw new IllegalArgumentException("Illegal load factor: " +
 274                                                loadFactor);
 275 
 276         // Find a power of 2 >= initialCapacity
 277         int capacity = 1;
 278         while (capacity < initialCapacity)
 279             capacity <<= 1;
 280 
 281         this.loadFactor = loadFactor;
 282         threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
 283         table = new Entry[capacity];
 284         useAltHashing = sun.misc.VM.isBooted() &&
 285                 (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
 286         init();
 287     }
 288 
 289     /**
 290      * Constructs an empty <tt>HashMap</tt> with the specified initial
 291      * capacity and the default load factor (0.75).
 292      *
 293      * @param  initialCapacity the initial capacity.
 294      * @throws IllegalArgumentException if the initial capacity is negative.
 295      */
 296     public HashMap(int initialCapacity) {
 297         this(initialCapacity, DEFAULT_LOAD_FACTOR);
 298     }
 299 
 300     /**
 301      * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 302      * (16) and the default load factor (0.75).
 303      */
 304     public HashMap() {
 305         this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
 306     }
 307 
 308     /**
 309      * Constructs a new <tt>HashMap</tt> with the same mappings as the
 310      * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 311      * default load factor (0.75) and an initial capacity sufficient to
 312      * hold the mappings in the specified <tt>Map</tt>.
 313      *
 314      * @param   m the map whose mappings are to be placed in this map
 315      * @throws  NullPointerException if the specified map is null
 316      */
 317     public HashMap(Map<? extends K, ? extends V> m) {
 318         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
 319                       DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
 320         putAllForCreate(m);
 321     }
 322 
 323     // internal utilities
 324 
 325     /**
 326      * Initialization hook for subclasses. This method is called
 327      * in all constructors and pseudo-constructors (clone, readObject)
 328      * after HashMap has been initialized but before any entries have
 329      * been inserted.  (In the absence of this method, readObject would
 330      * require explicit knowledge of subclasses.)
 331      */
 332     void init() {
 333     }
 334 
 335     /**
 336      * Retrieve object hash code and applies a supplemental hash function to the
 337      * result hash, which defends against poor quality hash functions.  This is
 338      * critical because HashMap uses power-of-two length hash tables, that
 339      * otherwise encounter collisions for hashCodes that do not differ
 340      * in lower bits. Note: Null keys always map to hash 0, thus index 0.
 341      */
 342     final int hash(Object k) {
 343         int h = 0;
 344         if (useAltHashing) {
 345             if (k instanceof String) {
 346                 return sun.misc.Hashing.stringHash32((String) k);
 347             }
 348             h = hashSeed;
 349         }
 350 
 351         h ^= k.hashCode();
 352 
 353         // This function ensures that hashCodes that differ only by
 354         // constant multiples at each bit position have a bounded
 355         // number of collisions (approximately 8 at default load factor).
 356         h ^= (h >>> 20) ^ (h >>> 12);
 357         return h ^ (h >>> 7) ^ (h >>> 4);
 358     }
 359 
 360     /**
 361      * Returns index for hash code h.
 362      */
 363     static int indexFor(int h, int length) {
 364         return h & (length-1);
 365     }
 366 
 367     /**
 368      * Returns the number of key-value mappings in this map.
 369      *
 370      * @return the number of key-value mappings in this map
 371      */
 372     public int size() {
 373         return size;
 374     }
 375 
 376     /**
 377      * Returns <tt>true</tt> if this map contains no key-value mappings.
 378      *
 379      * @return <tt>true</tt> if this map contains no key-value mappings
 380      */
 381     public boolean isEmpty() {
 382         return size == 0;
 383     }
 384 
 385     /**
 386      * Returns the value to which the specified key is mapped,
 387      * or {@code null} if this map contains no mapping for the key.
 388      *
 389      * <p>More formally, if this map contains a mapping from a key
 390      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 391      * key.equals(k))}, then this method returns {@code v}; otherwise
 392      * it returns {@code null}.  (There can be at most one such mapping.)
 393      *
 394      * <p>A return value of {@code null} does not <i>necessarily</i>
 395      * indicate that the map contains no mapping for the key; it's also
 396      * possible that the map explicitly maps the key to {@code null}.
 397      * The {@link #containsKey containsKey} operation may be used to
 398      * distinguish these two cases.
 399      *
 400      * @see #put(Object, Object)
 401      */
 402     public V get(Object key) {
 403         if (key == null)
 404             return getForNullKey();
 405         Entry<K,V> entry = getEntry(key);
 406 
 407         return null == entry ? null : entry.getValue();
 408     }
 409 
 410     /**
 411      * Offloaded version of get() to look up null keys.  Null keys map
 412      * to index 0.  This null case is split out into separate methods
 413      * for the sake of performance in the two most commonly used
 414      * operations (get and put), but incorporated with conditionals in
 415      * others.
 416      */
 417     private V getForNullKey() {
 418         for (Entry<K,V> e = table[0]; e != null; e = e.next) {
 419             if (e.key == null)
 420                 return e.value;
 421         }
 422         return null;
 423     }
 424 
 425     /**
 426      * Returns <tt>true</tt> if this map contains a mapping for the
 427      * specified key.
 428      *
 429      * @param   key   The key whose presence in this map is to be tested
 430      * @return <tt>true</tt> if this map contains a mapping for the specified
 431      * key.
 432      */
 433     public boolean containsKey(Object key) {
 434         return getEntry(key) != null;
 435     }
 436 
 437     /**
 438      * Returns the entry associated with the specified key in the
 439      * HashMap.  Returns null if the HashMap contains no mapping
 440      * for the key.
 441      */
 442     final Entry<K,V> getEntry(Object key) {
 443         int hash = (key == null) ? 0 : hash(key);
 444         for (Entry<K,V> e = table[indexFor(hash, table.length)];
 445              e != null;
 446              e = e.next) {
 447             Object k;
 448             if (e.hash == hash &&
 449                 ((k = e.key) == key || (key != null && key.equals(k))))
 450                 return e;
 451         }
 452         return null;
 453     }
 454 
 455 
 456     /**
 457      * Associates the specified value with the specified key in this map.
 458      * If the map previously contained a mapping for the key, the old
 459      * value is replaced.
 460      *
 461      * @param key key with which the specified value is to be associated
 462      * @param value value to be associated with the specified key
 463      * @return the previous value associated with <tt>key</tt>, or
 464      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 465      *         (A <tt>null</tt> return can also indicate that the map
 466      *         previously associated <tt>null</tt> with <tt>key</tt>.)
 467      */
 468     public V put(K key, V value) {
 469         if (key == null)
 470             return putForNullKey(value);
 471         int hash = hash(key);
 472         int i = indexFor(hash, table.length);
 473         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
 474             Object k;
 475             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
 476                 V oldValue = e.value;
 477                 e.value = value;
 478                 e.recordAccess(this);
 479                 return oldValue;
 480             }
 481         }
 482 
 483         modCount++;
 484         addEntry(hash, key, value, i);
 485         return null;
 486     }
 487 
 488     /**
 489      * Offloaded version of put for null keys
 490      */
 491     private V putForNullKey(V value) {
 492         for (Entry<K,V> e = table[0]; e != null; e = e.next) {
 493             if (e.key == null) {
 494                 V oldValue = e.value;
 495                 e.value = value;
 496                 e.recordAccess(this);
 497                 return oldValue;
 498             }
 499         }
 500         modCount++;
 501         addEntry(0, null, value, 0);
 502         return null;
 503     }
 504 
 505     /**
 506      * This method is used instead of put by constructors and
 507      * pseudoconstructors (clone, readObject).  It does not resize the table,
 508      * check for comodification, etc.  It calls createEntry rather than
 509      * addEntry.
 510      */
 511     private void putForCreate(K key, V value) {
 512         int hash = null == key ? 0 : hash(key);
 513         int i = indexFor(hash, table.length);
 514 
 515         /**
 516          * Look for preexisting entry for key.  This will never happen for
 517          * clone or deserialize.  It will only happen for construction if the
 518          * input Map is a sorted map whose ordering is inconsistent w/ equals.
 519          */
 520         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
 521             Object k;
 522             if (e.hash == hash &&
 523                 ((k = e.key) == key || (key != null && key.equals(k)))) {
 524                 e.value = value;
 525                 return;
 526             }
 527         }
 528 
 529         createEntry(hash, key, value, i);
 530     }
 531 
 532     private void putAllForCreate(Map<? extends K, ? extends V> m) {
 533         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
 534             putForCreate(e.getKey(), e.getValue());
 535     }
 536 
 537     /**
 538      * Rehashes the contents of this map into a new array with a
 539      * larger capacity.  This method is called automatically when the
 540      * number of keys in this map reaches its threshold.
 541      *
 542      * If current capacity is MAXIMUM_CAPACITY, this method does not
 543      * resize the map, but sets threshold to Integer.MAX_VALUE.
 544      * This has the effect of preventing future calls.
 545      *
 546      * @param newCapacity the new capacity, MUST be a power of two;
 547      *        must be greater than current capacity unless current
 548      *        capacity is MAXIMUM_CAPACITY (in which case value
 549      *        is irrelevant).
 550      */
 551     void resize(int newCapacity) {
 552         Entry[] oldTable = table;
 553         int oldCapacity = oldTable.length;
 554         if (oldCapacity == MAXIMUM_CAPACITY) {
 555             threshold = Integer.MAX_VALUE;
 556             return;
 557         }
 558 
 559         Entry[] newTable = new Entry[newCapacity];
 560         boolean oldAltHashing = useAltHashing;
 561         useAltHashing |= sun.misc.VM.isBooted() &&
 562                 (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
 563         boolean rehash = oldAltHashing ^ useAltHashing;
 564         transfer(newTable, rehash);
 565         table = newTable;
 566         threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
 567     }
 568 
 569     /**
 570      * Transfers all entries from current table to newTable.
 571      */
 572     void transfer(Entry[] newTable, boolean rehash) {
 573         int newCapacity = newTable.length;
 574         for (Entry<K,V> e : table) {
 575             while(null != e) {
 576                 Entry<K,V> next = e.next;
 577                 if (rehash) {
 578                     e.hash = null == e.key ? 0 : hash(e.key);
 579                 }
 580                 int i = indexFor(e.hash, newCapacity);
 581                 e.next = newTable[i];
 582                 newTable[i] = e;
 583                 e = next;
 584             }
 585         }
 586     }
 587 
 588     /**
 589      * Copies all of the mappings from the specified map to this map.
 590      * These mappings will replace any mappings that this map had for
 591      * any of the keys currently in the specified map.
 592      *
 593      * @param m mappings to be stored in this map
 594      * @throws NullPointerException if the specified map is null
 595      */
 596     public void putAll(Map<? extends K, ? extends V> m) {
 597         int numKeysToBeAdded = m.size();
 598         if (numKeysToBeAdded == 0)
 599             return;
 600 
 601         /*
 602          * Expand the map if the map if the number of mappings to be added
 603          * is greater than or equal to threshold.  This is conservative; the
 604          * obvious condition is (m.size() + size) >= threshold, but this
 605          * condition could result in a map with twice the appropriate capacity,
 606          * if the keys to be added overlap with the keys already in this map.
 607          * By using the conservative calculation, we subject ourself
 608          * to at most one extra resize.
 609          */
 610         if (numKeysToBeAdded > threshold) {
 611             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
 612             if (targetCapacity > MAXIMUM_CAPACITY)
 613                 targetCapacity = MAXIMUM_CAPACITY;
 614             int newCapacity = table.length;
 615             while (newCapacity < targetCapacity)
 616                 newCapacity <<= 1;
 617             if (newCapacity > table.length)
 618                 resize(newCapacity);
 619         }
 620 
 621         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
 622             put(e.getKey(), e.getValue());
 623     }
 624 
 625     /**
 626      * Removes the mapping for the specified key from this map if present.
 627      *
 628      * @param  key key whose mapping is to be removed from the map
 629      * @return the previous value associated with <tt>key</tt>, or
 630      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 631      *         (A <tt>null</tt> return can also indicate that the map
 632      *         previously associated <tt>null</tt> with <tt>key</tt>.)
 633      */
 634     public V remove(Object key) {
 635         Entry<K,V> e = removeEntryForKey(key);
 636         return (e == null ? null : e.value);
 637     }
 638 
 639     /**
 640      * Removes and returns the entry associated with the specified key
 641      * in the HashMap.  Returns null if the HashMap contains no mapping
 642      * for this key.
 643      */
 644     final Entry<K,V> removeEntryForKey(Object key) {
 645         int hash = (key == null) ? 0 : hash(key);
 646         int i = indexFor(hash, table.length);
 647         Entry<K,V> prev = table[i];
 648         Entry<K,V> e = prev;
 649 
 650         while (e != null) {
 651             Entry<K,V> next = e.next;
 652             Object k;
 653             if (e.hash == hash &&
 654                 ((k = e.key) == key || (key != null && key.equals(k)))) {
 655                 modCount++;
 656                 size--;
 657                 if (prev == e)
 658                     table[i] = next;
 659                 else
 660                     prev.next = next;
 661                 e.recordRemoval(this);
 662                 return e;
 663             }
 664             prev = e;
 665             e = next;
 666         }
 667 
 668         return e;
 669     }
 670 
 671     /**
 672      * Special version of remove for EntrySet using {@code Map.Entry.equals()}
 673      * for matching.
 674      */
 675     final Entry<K,V> removeMapping(Object o) {
 676         if (!(o instanceof Map.Entry))
 677             return null;
 678 
 679         Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
 680         Object key = entry.getKey();
 681         int hash = (key == null) ? 0 : hash(key);
 682         int i = indexFor(hash, table.length);
 683         Entry<K,V> prev = table[i];
 684         Entry<K,V> e = prev;
 685 
 686         while (e != null) {
 687             Entry<K,V> next = e.next;
 688             if (e.hash == hash && e.equals(entry)) {
 689                 modCount++;
 690                 size--;
 691                 if (prev == e)
 692                     table[i] = next;
 693                 else
 694                     prev.next = next;
 695                 e.recordRemoval(this);
 696                 return e;
 697             }
 698             prev = e;
 699             e = next;
 700         }
 701 
 702         return e;
 703     }
 704 
 705     /**
 706      * Removes all of the mappings from this map.
 707      * The map will be empty after this call returns.
 708      */
 709     public void clear() {
 710         modCount++;
 711         Entry[] tab = table;
 712         for (int i = 0; i < tab.length; i++)
 713             tab[i] = null;
 714         size = 0;
 715     }
 716 
 717     /**
 718      * Returns <tt>true</tt> if this map maps one or more keys to the
 719      * specified value.
 720      *
 721      * @param value value whose presence in this map is to be tested
 722      * @return <tt>true</tt> if this map maps one or more keys to the
 723      *         specified value
 724      */
 725     public boolean containsValue(Object value) {
 726         if (value == null)
 727             return containsNullValue();
 728 
 729         Entry[] tab = table;
 730         for (int i = 0; i < tab.length ; i++)
 731             for (Entry e = tab[i] ; e != null ; e = e.next)
 732                 if (value.equals(e.value))
 733                     return true;
 734         return false;
 735     }
 736 
 737     /**
 738      * Special-case code for containsValue with null argument
 739      */
 740     private boolean containsNullValue() {
 741         Entry[] tab = table;
 742         for (int i = 0; i < tab.length ; i++)
 743             for (Entry e = tab[i] ; e != null ; e = e.next)
 744                 if (e.value == null)
 745                     return true;
 746         return false;
 747     }
 748 
 749     /**
 750      * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
 751      * values themselves are not cloned.
 752      *
 753      * @return a shallow copy of this map
 754      */
 755     public Object clone() {
 756         HashMap<K,V> result = null;
 757         try {
 758             result = (HashMap<K,V>)super.clone();
 759         } catch (CloneNotSupportedException e) {
 760             // assert false;
 761         }
 762         result.table = new Entry[table.length];
 763         result.entrySet = null;
 764         result.modCount = 0;
 765         result.size = 0;
 766         result.init();
 767         result.putAllForCreate(this);
 768 
 769         return result;
 770     }
 771 
 772     static class Entry<K,V> implements Map.Entry<K,V> {
 773         final K key;
 774         V value;
 775         Entry<K,V> next;
 776         int hash;
 777 
 778         /**
 779          * Creates new entry.
 780          */
 781         Entry(int h, K k, V v, Entry<K,V> n) {
 782             value = v;
 783             next = n;
 784             key = k;
 785             hash = h;
 786         }
 787 
 788         public final K getKey() {
 789             return key;
 790         }
 791 
 792         public final V getValue() {
 793             return value;
 794         }
 795 
 796         public final V setValue(V newValue) {
 797             V oldValue = value;
 798             value = newValue;
 799             return oldValue;
 800         }
 801 
 802         public final boolean equals(Object o) {
 803             if (!(o instanceof Map.Entry))
 804                 return false;
 805             Map.Entry e = (Map.Entry)o;
 806             Object k1 = getKey();
 807             Object k2 = e.getKey();
 808             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
 809                 Object v1 = getValue();
 810                 Object v2 = e.getValue();
 811                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
 812                     return true;
 813             }
 814             return false;
 815         }
 816 
 817         public final int hashCode() {
 818             return (key==null   ? 0 : key.hashCode()) ^
 819                    (value==null ? 0 : value.hashCode());
 820         }
 821 
 822         public final String toString() {
 823             return getKey() + "=" + getValue();
 824         }
 825 
 826         /**
 827          * This method is invoked whenever the value in an entry is
 828          * overwritten by an invocation of put(k,v) for a key k that's already
 829          * in the HashMap.
 830          */
 831         void recordAccess(HashMap<K,V> m) {
 832         }
 833 
 834         /**
 835          * This method is invoked whenever the entry is
 836          * removed from the table.
 837          */
 838         void recordRemoval(HashMap<K,V> m) {
 839         }
 840     }
 841 
 842     /**
 843      * Adds a new entry with the specified key, value and hash code to
 844      * the specified bucket.  It is the responsibility of this
 845      * method to resize the table if appropriate.
 846      *
 847      * Subclass overrides this to alter the behavior of put method.
 848      */
 849     void addEntry(int hash, K key, V value, int bucketIndex) {
 850         if ((size >= threshold) && (null != table[bucketIndex])) {
 851             resize(2 * table.length);
 852             hash = (null != key) ? hash(key) : 0;
 853             bucketIndex = indexFor(hash, table.length);
 854         }
 855 
 856         createEntry(hash, key, value, bucketIndex);
 857     }
 858 
 859     /**
 860      * Like addEntry except that this version is used when creating entries
 861      * as part of Map construction or "pseudo-construction" (cloning,
 862      * deserialization).  This version needn't worry about resizing the table.
 863      *
 864      * Subclass overrides this to alter the behavior of HashMap(Map),
 865      * clone, and readObject.
 866      */
 867     void createEntry(int hash, K key, V value, int bucketIndex) {
 868         Entry<K,V> e = table[bucketIndex];
 869         table[bucketIndex] = new Entry<>(hash, key, value, e);
 870         size++;
 871     }
 872 
 873     private abstract class HashIterator<E> implements Iterator<E> {
 874         Entry<K,V> next;        // next entry to return
 875         int expectedModCount;   // For fast-fail
 876         int index;              // current slot
 877         Entry<K,V> current;     // current entry
 878 
 879         HashIterator() {
 880             expectedModCount = modCount;
 881             if (size > 0) { // advance to first entry
 882                 Entry[] t = table;
 883                 while (index < t.length && (next = t[index++]) == null)
 884                     ;
 885             }
 886         }
 887 
 888         public final boolean hasNext() {
 889             return next != null;
 890         }
 891 
 892         final Entry<K,V> nextEntry() {
 893             if (modCount != expectedModCount)
 894                 throw new ConcurrentModificationException();
 895             Entry<K,V> e = next;
 896             if (e == null)
 897                 throw new NoSuchElementException();
 898 
 899             if ((next = e.next) == null) {
 900                 Entry[] t = table;
 901                 while (index < t.length && (next = t[index++]) == null)
 902                     ;
 903             }
 904             current = e;
 905             return e;
 906         }
 907 
 908         public void remove() {
 909             if (current == null)
 910                 throw new IllegalStateException();
 911             if (modCount != expectedModCount)
 912                 throw new ConcurrentModificationException();
 913             Object k = current.key;
 914             current = null;
 915             HashMap.this.removeEntryForKey(k);
 916             expectedModCount = modCount;
 917         }
 918     }
 919 
 920     private final class ValueIterator extends HashIterator<V> {
 921         public V next() {
 922             return nextEntry().value;
 923         }
 924     }
 925 
 926     private final class KeyIterator extends HashIterator<K> {
 927         public K next() {
 928             return nextEntry().getKey();
 929         }
 930     }
 931 
 932     private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
 933         public Map.Entry<K,V> next() {
 934             return nextEntry();
 935         }
 936     }
 937 
 938     // Subclass overrides these to alter behavior of views' iterator() method
 939     Iterator<K> newKeyIterator()   {
 940         return new KeyIterator();
 941     }
 942     Iterator<V> newValueIterator()   {
 943         return new ValueIterator();
 944     }
 945     Iterator<Map.Entry<K,V>> newEntryIterator()   {
 946         return new EntryIterator();
 947     }
 948 
 949 
 950     // Views
 951 
 952     private transient Set<Map.Entry<K,V>> entrySet = null;
 953 
 954     /**
 955      * Returns a {@link Set} view of the keys contained in this map.
 956      * The set is backed by the map, so changes to the map are
 957      * reflected in the set, and vice-versa.  If the map is modified
 958      * while an iteration over the set is in progress (except through
 959      * the iterator's own <tt>remove</tt> operation), the results of
 960      * the iteration are undefined.  The set supports element removal,
 961      * which removes the corresponding mapping from the map, via the
 962      * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
 963      * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
 964      * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
 965      * operations.
 966      */
 967     public Set<K> keySet() {
 968         Set<K> ks = keySet;
 969         return (ks != null ? ks : (keySet = new KeySet()));
 970     }
 971 
 972     private final class KeySet extends AbstractSet<K> {
 973         public Iterator<K> iterator() {
 974             return newKeyIterator();
 975         }
 976         public int size() {
 977             return size;
 978         }
 979         public boolean contains(Object o) {
 980             return containsKey(o);
 981         }
 982         public boolean remove(Object o) {
 983             return HashMap.this.removeEntryForKey(o) != null;
 984         }
 985         public void clear() {
 986             HashMap.this.clear();
 987         }
 988     }
 989 
 990     /**
 991      * Returns a {@link Collection} view of the values contained in this map.
 992      * The collection is backed by the map, so changes to the map are
 993      * reflected in the collection, and vice-versa.  If the map is
 994      * modified while an iteration over the collection is in progress
 995      * (except through the iterator's own <tt>remove</tt> operation),
 996      * the results of the iteration are undefined.  The collection
 997      * supports element removal, which removes the corresponding
 998      * mapping from the map, via the <tt>Iterator.remove</tt>,
 999      * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1000      * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
1001      * support the <tt>add</tt> or <tt>addAll</tt> operations.
1002      */
1003     public Collection<V> values() {
1004         Collection<V> vs = values;
1005         return (vs != null ? vs : (values = new Values()));
1006     }
1007 
1008     private final class Values extends AbstractCollection<V> {
1009         public Iterator<V> iterator() {
1010             return newValueIterator();
1011         }
1012         public int size() {
1013             return size;
1014         }
1015         public boolean contains(Object o) {
1016             return containsValue(o);
1017         }
1018         public void clear() {
1019             HashMap.this.clear();
1020         }
1021     }
1022 
1023     /**
1024      * Returns a {@link Set} view of the mappings contained in this map.
1025      * The set is backed by the map, so changes to the map are
1026      * reflected in the set, and vice-versa.  If the map is modified
1027      * while an iteration over the set is in progress (except through
1028      * the iterator's own <tt>remove</tt> operation, or through the
1029      * <tt>setValue</tt> operation on a map entry returned by the
1030      * iterator) the results of the iteration are undefined.  The set
1031      * supports element removal, which removes the corresponding
1032      * mapping from the map, via the <tt>Iterator.remove</tt>,
1033      * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
1034      * <tt>clear</tt> operations.  It does not support the
1035      * <tt>add</tt> or <tt>addAll</tt> operations.
1036      *
1037      * @return a set view of the mappings contained in this map
1038      */
1039     public Set<Map.Entry<K,V>> entrySet() {
1040         return entrySet0();
1041     }
1042 
1043     private Set<Map.Entry<K,V>> entrySet0() {
1044         Set<Map.Entry<K,V>> es = entrySet;
1045         return es != null ? es : (entrySet = new EntrySet());
1046     }
1047 
1048     private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1049         public Iterator<Map.Entry<K,V>> iterator() {
1050             return newEntryIterator();
1051         }
1052         public boolean contains(Object o) {
1053             if (!(o instanceof Map.Entry))
1054                 return false;
1055             Map.Entry<K,V> e = (Map.Entry<K,V>) o;
1056             Entry<K,V> candidate = getEntry(e.getKey());
1057             return candidate != null && candidate.equals(e);
1058         }
1059         public boolean remove(Object o) {
1060             return removeMapping(o) != null;
1061         }
1062         public int size() {
1063             return size;
1064         }
1065         public void clear() {
1066             HashMap.this.clear();
1067         }
1068     }
1069 
1070     /**
1071      * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
1072      * serialize it).
1073      *
1074      * @serialData The <i>capacity</i> of the HashMap (the length of the
1075      *             bucket array) is emitted (int), followed by the
1076      *             <i>size</i> (an int, the number of key-value
1077      *             mappings), followed by the key (Object) and value (Object)
1078      *             for each key-value mapping.  The key-value mappings are
1079      *             emitted in no particular order.
1080      */
1081     private void writeObject(java.io.ObjectOutputStream s)
1082         throws IOException
1083     {
1084         Iterator<Map.Entry<K,V>> i =
1085             (size > 0) ? entrySet0().iterator() : null;
1086 
1087         // Write out the threshold, loadfactor, and any hidden stuff
1088         s.defaultWriteObject();
1089 
1090         // Write out number of buckets
1091         s.writeInt(table.length);
1092 
1093         // Write out size (number of Mappings)
1094         s.writeInt(size);
1095 
1096         // Write out keys and values (alternating)
1097         if (size > 0) {
1098             for(Map.Entry<K,V> e : entrySet0()) {
1099                 s.writeObject(e.getKey());
1100                 s.writeObject(e.getValue());
1101             }
1102         }
1103     }
1104 
1105     private static final long serialVersionUID = 362498820763181265L;
1106 
1107     /**
1108      * Reconstitute the {@code HashMap} instance from a stream (i.e.,
1109      * deserialize it).
1110      */
1111     private void readObject(java.io.ObjectInputStream s)
1112          throws IOException, ClassNotFoundException
1113     {
1114         // Read in the threshold (ignored), loadfactor, and any hidden stuff
1115         s.defaultReadObject();
1116         if (loadFactor <= 0 || Float.isNaN(loadFactor))
1117             throw new InvalidObjectException("Illegal load factor: " +
1118                                                loadFactor);
1119 
1120         // set hashSeed (can only happen after VM boot)
1121         Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
1122                 sun.misc.Hashing.randomHashSeed(this));
1123 
1124         // Read in number of buckets and allocate the bucket array;
1125         s.readInt(); // ignored
1126 
1127         // Read number of mappings
1128         int mappings = s.readInt();
1129         if (mappings < 0)
1130             throw new InvalidObjectException("Illegal mappings count: " +
1131                                                mappings);
1132 
1133         int initialCapacity = (int) Math.min(
1134                 // capacity chosen by number of mappings
1135                 // and desired load (if >= 0.25)
1136                 mappings * Math.min(1 / loadFactor, 4.0f),
1137                 // we have limits...
1138                 HashMap.MAXIMUM_CAPACITY);
1139         int capacity = 1;
1140         // find smallest power of two which holds all mappings
1141         while (capacity < initialCapacity) {
1142             capacity <<= 1;
1143         }
1144 
1145         table = new Entry[capacity];
1146         threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
1147         useAltHashing = sun.misc.VM.isBooted() &&
1148                 (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
1149 
1150         init();  // Give subclass a chance to do its thing.
1151 
1152         // Read the keys and values, and put the mappings in the HashMap
1153         for (int i=0; i<mappings; i++) {
1154             K key = (K) s.readObject();
1155             V value = (V) s.readObject();
1156             putForCreate(key, value);
1157         }
1158     }
1159 
1160     // These methods are used when serializing HashSets
1161     int   capacity()     { return table.length; }
1162     float loadFactor()   { return loadFactor;   }
1163 }