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<?,?>[] 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     private static class Holder {
 179          /**
 180          *
 181          */
 182         static final sun.misc.Unsafe UNSAFE;
 183 
 184         /**
 185          * Offset of "final" hashSeed field we must set in
 186          * readObject() method.
 187          */
 188         static final long HASHSEED_OFFSET;
 189 
 190         static {
 191             try {
 192                 UNSAFE = sun.misc.Unsafe.getUnsafe();
 193                 HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
 194                     HashMap.class.getDeclaredField("hashSeed"));
 195             } catch (NoSuchFieldException | SecurityException e) {
 196                 throw new InternalError("Failed to record hashSeed offset", e);
 197             }
 198         }
 199     }
 200 
 201     /**
 202      * A randomizing value associated with this instance that is applied to
 203      * hash code of keys to make hash collisions harder to find.
 204      */
 205     transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
 206 
 207     /**
 208      * Constructs an empty <tt>HashMap</tt> with the specified initial
 209      * capacity and load factor.
 210      *
 211      * @param  initialCapacity the initial capacity
 212      * @param  loadFactor      the load factor
 213      * @throws IllegalArgumentException if the initial capacity is negative
 214      *         or the load factor is nonpositive
 215      */
 216     public HashMap(int initialCapacity, float loadFactor) {
 217         if (initialCapacity < 0)
 218             throw new IllegalArgumentException("Illegal initial capacity: " +
 219                                                initialCapacity);
 220         if (initialCapacity > MAXIMUM_CAPACITY)
 221             initialCapacity = MAXIMUM_CAPACITY;
 222         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 223             throw new IllegalArgumentException("Illegal load factor: " +
 224                                                loadFactor);
 225 
 226         // Find a power of 2 >= initialCapacity
 227         int capacity = 1;
 228         while (capacity < initialCapacity)
 229             capacity <<= 1;
 230 
 231         this.loadFactor = loadFactor;
 232         threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
 233         table = new Entry[capacity];
 234         init();
 235     }
 236 
 237     /**
 238      * Constructs an empty <tt>HashMap</tt> with the specified initial
 239      * capacity and the default load factor (0.75).
 240      *
 241      * @param  initialCapacity the initial capacity.
 242      * @throws IllegalArgumentException if the initial capacity is negative.
 243      */
 244     public HashMap(int initialCapacity) {
 245         this(initialCapacity, DEFAULT_LOAD_FACTOR);
 246     }
 247 
 248     /**
 249      * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 250      * (16) and the default load factor (0.75).
 251      */
 252     public HashMap() {
 253         this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
 254     }
 255 
 256     /**
 257      * Constructs a new <tt>HashMap</tt> with the same mappings as the
 258      * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
 259      * default load factor (0.75) and an initial capacity sufficient to
 260      * hold the mappings in the specified <tt>Map</tt>.
 261      *
 262      * @param   m the map whose mappings are to be placed in this map
 263      * @throws  NullPointerException if the specified map is null
 264      */
 265     public HashMap(Map<? extends K, ? extends V> m) {
 266         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
 267                       DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
 268         putAllForCreate(m);
 269     }
 270 
 271     // internal utilities
 272 
 273     /**
 274      * Initialization hook for subclasses. This method is called
 275      * in all constructors and pseudo-constructors (clone, readObject)
 276      * after HashMap has been initialized but before any entries have
 277      * been inserted.  (In the absence of this method, readObject would
 278      * require explicit knowledge of subclasses.)
 279      */
 280     void init() {
 281     }
 282 
 283     /**
 284      * Retrieve object hash code and applies a supplemental hash function to the
 285      * result hash, which defends against poor quality hash functions.  This is
 286      * critical because HashMap uses power-of-two length hash tables, that
 287      * otherwise encounter collisions for hashCodes that do not differ
 288      * in lower bits.
 289      */
 290     final int hash(Object k) {
 291         int h = hashSeed;
 292         if (k instanceof String) {
 293             return ((String)k).hash32();
 294         }
 295 
 296         h ^= k.hashCode();
 297 
 298         // This function ensures that hashCodes that differ only by
 299         // constant multiples at each bit position have a bounded
 300         // number of collisions (approximately 8 at default load factor).
 301         h ^= (h >>> 20) ^ (h >>> 12);
 302         return h ^ (h >>> 7) ^ (h >>> 4);
 303     }
 304 
 305     /**
 306      * Returns index for hash code h.
 307      */
 308     static int indexFor(int h, int length) {
 309         return h & (length-1);
 310     }
 311 
 312     /**
 313      * Returns the number of key-value mappings in this map.
 314      *
 315      * @return the number of key-value mappings in this map
 316      */
 317     public int size() {
 318         return size;
 319     }
 320 
 321     /**
 322      * Returns <tt>true</tt> if this map contains no key-value mappings.
 323      *
 324      * @return <tt>true</tt> if this map contains no key-value mappings
 325      */
 326     public boolean isEmpty() {
 327         return size == 0;
 328     }
 329 
 330     /**
 331      * Returns the value to which the specified key is mapped,
 332      * or {@code null} if this map contains no mapping for the key.
 333      *
 334      * <p>More formally, if this map contains a mapping from a key
 335      * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 336      * key.equals(k))}, then this method returns {@code v}; otherwise
 337      * it returns {@code null}.  (There can be at most one such mapping.)
 338      *
 339      * <p>A return value of {@code null} does not <i>necessarily</i>
 340      * indicate that the map contains no mapping for the key; it's also
 341      * possible that the map explicitly maps the key to {@code null}.
 342      * The {@link #containsKey containsKey} operation may be used to
 343      * distinguish these two cases.
 344      *
 345      * @see #put(Object, Object)
 346      */
 347     @SuppressWarnings("unchecked")
 348     public V get(Object key) {
 349         Entry<K,V> entry = getEntry(key);
 350 
 351         return null == entry ? null : entry.getValue();
 352     }
 353 
 354     /**
 355      * Returns <tt>true</tt> if this map contains a mapping for the
 356      * specified key.
 357      *
 358      * @param   key   The key whose presence in this map is to be tested
 359      * @return <tt>true</tt> if this map contains a mapping for the specified
 360      * key.
 361      */
 362     public boolean containsKey(Object key) {
 363         return getEntry(key) != null;
 364     }
 365 
 366     /**
 367      * Returns the entry associated with the specified key in the
 368      * HashMap.  Returns null if the HashMap contains no mapping
 369      * for the key.
 370      */
 371     @SuppressWarnings("unchecked")
 372     final Entry<K,V> getEntry(Object key) {
 373         int hash = (key == null) ? 0 : hash(key);
 374         for (Entry<?,?> e = table[indexFor(hash, table.length)];
 375              e != null;
 376              e = e.next) {
 377             Object k;
 378             if (e.hash == hash &&
 379                 ((k = e.key) == key || (key != null && key.equals(k))))
 380                 return (Entry<K,V>)e;
 381         }
 382         return null;
 383     }
 384 
 385 
 386     /**
 387      * Associates the specified value with the specified key in this map.
 388      * If the map previously contained a mapping for the key, the old
 389      * value is replaced.
 390      *
 391      * @param key key with which the specified value is to be associated
 392      * @param value value to be associated with the specified key
 393      * @return the previous value associated with <tt>key</tt>, or
 394      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 395      *         (A <tt>null</tt> return can also indicate that the map
 396      *         previously associated <tt>null</tt> with <tt>key</tt>.)
 397      */
 398     public V put(K key, V value) {
 399         if (key == null)
 400             return putForNullKey(value);
 401         int hash = hash(key);
 402         int i = indexFor(hash, table.length);
 403         @SuppressWarnings("unchecked")
 404         Entry<K,V> e = (Entry<K,V>)table[i];
 405         for(; e != null; e = e.next) {
 406             Object k;
 407             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
 408                 V oldValue = e.value;
 409                 e.value = value;
 410                 e.recordAccess(this);
 411                 return oldValue;
 412             }
 413         }
 414 
 415         modCount++;
 416         addEntry(hash, key, value, i);
 417         return null;
 418     }
 419 
 420     /**
 421      * Offloaded version of put for null keys
 422      */
 423     private V putForNullKey(V value) {
 424         @SuppressWarnings("unchecked")
 425         Entry<K,V> e = (Entry<K,V>)table[0];
 426         for(; e != null; e = e.next) {
 427             if (e.key == null) {
 428                 V oldValue = e.value;
 429                 e.value = value;
 430                 e.recordAccess(this);
 431                 return oldValue;
 432             }
 433         }
 434         modCount++;
 435         addEntry(0, null, value, 0);
 436         return null;
 437     }
 438 
 439     /**
 440      * This method is used instead of put by constructors and
 441      * pseudoconstructors (clone, readObject).  It does not resize the table,
 442      * check for comodification, etc.  It calls createEntry rather than
 443      * addEntry.
 444      */
 445     private void putForCreate(K key, V value) {
 446         int hash = null == key ? 0 : hash(key);
 447         int i = indexFor(hash, table.length);
 448 
 449         /**
 450          * Look for preexisting entry for key.  This will never happen for
 451          * clone or deserialize.  It will only happen for construction if the
 452          * input Map is a sorted map whose ordering is inconsistent w/ equals.
 453          */
 454         for (@SuppressWarnings("unchecked")
 455              Entry<?,V> e = (Entry<?,V>)table[i]; e != null; e = e.next) {
 456             Object k;
 457             if (e.hash == hash &&
 458                 ((k = e.key) == key || (key != null && key.equals(k)))) {
 459                 e.value = value;
 460                 return;
 461             }
 462         }
 463 
 464         createEntry(hash, key, value, i);
 465     }
 466 
 467     private void putAllForCreate(Map<? extends K, ? extends V> m) {
 468         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
 469             putForCreate(e.getKey(), e.getValue());
 470     }
 471 
 472     /**
 473      * Rehashes the contents of this map into a new array with a
 474      * larger capacity.  This method is called automatically when the
 475      * number of keys in this map reaches its threshold.
 476      *
 477      * If current capacity is MAXIMUM_CAPACITY, this method does not
 478      * resize the map, but sets threshold to Integer.MAX_VALUE.
 479      * This has the effect of preventing future calls.
 480      *
 481      * @param newCapacity the new capacity, MUST be a power of two;
 482      *        must be greater than current capacity unless current
 483      *        capacity is MAXIMUM_CAPACITY (in which case value
 484      *        is irrelevant).
 485      */
 486     void resize(int newCapacity) {
 487         Entry<?,?>[] oldTable = table;
 488         int oldCapacity = oldTable.length;
 489         if (oldCapacity == MAXIMUM_CAPACITY) {
 490             threshold = Integer.MAX_VALUE;
 491             return;
 492         }
 493 
 494         Entry<?,?>[] newTable = new Entry<?,?>[newCapacity];
 495         transfer(newTable);
 496         table = newTable;
 497         threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
 498     }
 499 
 500     /**
 501      * Transfers all entries from current table to newTable.
 502      */
 503     @SuppressWarnings("unchecked")
 504     void transfer(Entry<?,?>[] newTable) {
 505         Entry<?,?>[] src = table;
 506         int newCapacity = newTable.length;
 507         for (int j = 0; j < src.length; j++ ) {
 508             Entry<K,V> e = (Entry<K,V>) src[j];
 509             while(null != e) {
 510                 Entry<K,V> next = e.next;
 511                 int i = indexFor(e.hash, newCapacity);
 512                 e.next = (Entry<K,V>) newTable[i];
 513                 newTable[i] = e;
 514                 e = next;
 515             }
 516         }
 517         Arrays.fill(table, null);
 518     }
 519 
 520     /**
 521      * Copies all of the mappings from the specified map to this map.
 522      * These mappings will replace any mappings that this map had for
 523      * any of the keys currently in the specified map.
 524      *
 525      * @param m mappings to be stored in this map
 526      * @throws NullPointerException if the specified map is null
 527      */
 528     public void putAll(Map<? extends K, ? extends V> m) {
 529         int numKeysToBeAdded = m.size();
 530         if (numKeysToBeAdded == 0)
 531             return;
 532 
 533         /*
 534          * Expand the map if the map if the number of mappings to be added
 535          * is greater than or equal to threshold.  This is conservative; the
 536          * obvious condition is (m.size() + size) >= threshold, but this
 537          * condition could result in a map with twice the appropriate capacity,
 538          * if the keys to be added overlap with the keys already in this map.
 539          * By using the conservative calculation, we subject ourself
 540          * to at most one extra resize.
 541          */
 542         if (numKeysToBeAdded > threshold) {
 543             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
 544             if (targetCapacity > MAXIMUM_CAPACITY)
 545                 targetCapacity = MAXIMUM_CAPACITY;
 546             int newCapacity = table.length;
 547             while (newCapacity < targetCapacity)
 548                 newCapacity <<= 1;
 549             if (newCapacity > table.length)
 550                 resize(newCapacity);
 551         }
 552 
 553         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
 554             put(e.getKey(), e.getValue());
 555     }
 556 
 557     /**
 558      * Removes the mapping for the specified key from this map if present.
 559      *
 560      * @param  key key whose mapping is to be removed from the map
 561      * @return the previous value associated with <tt>key</tt>, or
 562      *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 563      *         (A <tt>null</tt> return can also indicate that the map
 564      *         previously associated <tt>null</tt> with <tt>key</tt>.)
 565      */
 566     public V remove(Object key) {
 567         Entry<K,V> e = removeEntryForKey(key);
 568         return (e == null ? null : e.value);
 569     }
 570 
 571     /**
 572      * Removes and returns the entry associated with the specified key
 573      * in the HashMap.  Returns null if the HashMap contains no mapping
 574      * for this key.
 575      */
 576     final Entry<K,V> removeEntryForKey(Object key) {
 577         int hash = (key == null) ? 0 : hash(key);
 578         int i = indexFor(hash, table.length);
 579         @SuppressWarnings("unchecked")
 580             Entry<K,V> prev = (Entry<K,V>)table[i];
 581         Entry<K,V> e = prev;
 582 
 583         while (e != null) {
 584             Entry<K,V> next = e.next;
 585             Object k;
 586             if (e.hash == hash &&
 587                 ((k = e.key) == key || (key != null && key.equals(k)))) {
 588                 modCount++;
 589                 size--;
 590                 if (prev == e)
 591                     table[i] = next;
 592                 else
 593                     prev.next = next;
 594                 e.recordRemoval(this);
 595                 return e;
 596             }
 597             prev = e;
 598             e = next;
 599         }
 600 
 601         return e;
 602     }
 603 
 604     /**
 605      * Special version of remove for EntrySet using {@code Map.Entry.equals()}
 606      * for matching.
 607      */
 608     final Entry<K,V> removeMapping(Object o) {
 609         if (!(o instanceof Map.Entry))
 610             return null;
 611 
 612         Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
 613         Object key = entry.getKey();
 614         int hash = (key == null) ? 0 : hash(key.hashCode());
 615         int i = indexFor(hash, table.length);
 616         @SuppressWarnings("unchecked")
 617             Entry<K,V> prev = (Entry<K,V>)table[i];
 618         Entry<K,V> e = prev;
 619 
 620         while (e != null) {
 621             Entry<K,V> next = e.next;
 622             if (e.hash == hash && e.equals(entry)) {
 623                 modCount++;
 624                 size--;
 625                 if (prev == e)
 626                     table[i] = next;
 627                 else
 628                     prev.next = next;
 629                 e.recordRemoval(this);
 630                 return e;
 631             }
 632             prev = e;
 633             e = next;
 634         }
 635 
 636         return e;
 637     }
 638 
 639     /**
 640      * Removes all of the mappings from this map.
 641      * The map will be empty after this call returns.
 642      */
 643     public void clear() {
 644         modCount++;
 645         Entry<?,?>[] tab = table;
 646         for (int i = 0; i < tab.length; i++)
 647             tab[i] = null;
 648         size = 0;
 649     }
 650 
 651     /**
 652      * Returns <tt>true</tt> if this map maps one or more keys to the
 653      * specified value.
 654      *
 655      * @param value value whose presence in this map is to be tested
 656      * @return <tt>true</tt> if this map maps one or more keys to the
 657      *         specified value
 658      */
 659     public boolean containsValue(Object value) {
 660         if (value == null)
 661             return containsNullValue();
 662 
 663         Entry<?,?>[] tab = table;
 664         for (int i = 0; i < tab.length ; i++)
 665             for (Entry<?,?> e = tab[i] ; e != null ; e = e.next)
 666                 if (value.equals(e.value))
 667                     return true;
 668         return false;
 669     }
 670 
 671     /**
 672      * Special-case code for containsValue with null argument
 673      */
 674     private boolean containsNullValue() {
 675         Entry<?,?>[] tab = table;
 676         for (int i = 0; i < tab.length ; i++)
 677             for (Entry<?,?> e = tab[i] ; e != null ; e = e.next)
 678                 if (e.value == null)
 679                     return true;
 680         return false;
 681     }
 682 
 683     /**
 684      * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
 685      * values themselves are not cloned.
 686      *
 687      * @return a shallow copy of this map
 688      */
 689     @SuppressWarnings("unchecked")
 690     public Object clone() {
 691         HashMap<K,V> result = null;
 692         try {
 693             result = (HashMap<K,V>)super.clone();
 694         } catch (CloneNotSupportedException e) {
 695             // assert false;
 696         }
 697         result.table = new Entry<?,?>[table.length];
 698         result.entrySet = null;
 699         result.modCount = 0;
 700         result.size = 0;
 701         result.init();
 702         result.putAllForCreate(this);
 703 
 704         return result;
 705     }
 706 
 707     static class Entry<K,V> implements Map.Entry<K,V> {
 708         final K key;
 709         V value;
 710         Entry<K,V> next;
 711         final int hash;
 712 
 713         /**
 714          * Creates new entry.
 715          */
 716         Entry(int h, K k, V v, Entry<K,V> n) {
 717             value = v;
 718             next = n;
 719             key = k;
 720             hash = h;
 721         }
 722 
 723         public final K getKey() {
 724             return key;
 725         }
 726 
 727         public final V getValue() {
 728             return value;
 729         }
 730 
 731         public final V setValue(V newValue) {
 732             V oldValue = value;
 733             value = newValue;
 734             return oldValue;
 735         }
 736 
 737         public final boolean equals(Object o) {
 738             if (!(o instanceof Map.Entry))
 739                 return false;
 740             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
 741             Object k1 = getKey();
 742             Object k2 = e.getKey();
 743             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
 744                 Object v1 = getValue();
 745                 Object v2 = e.getValue();
 746                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
 747                     return true;
 748             }
 749             return false;
 750         }
 751 
 752         public final int hashCode() {
 753             return (key==null   ? 0 : key.hashCode()) ^
 754                    (value==null ? 0 : value.hashCode());
 755         }
 756 
 757         public final String toString() {
 758             return getKey() + "=" + getValue();
 759         }
 760 
 761         /**
 762          * This method is invoked whenever the value in an entry is
 763          * overwritten by an invocation of put(k,v) for a key k that's already
 764          * in the HashMap.
 765          */
 766         void recordAccess(HashMap<K,V> m) {
 767         }
 768 
 769         /**
 770          * This method is invoked whenever the entry is
 771          * removed from the table.
 772          */
 773         void recordRemoval(HashMap<K,V> m) {
 774         }
 775     }
 776 
 777     /**
 778      * Adds a new entry with the specified key, value and hash code to
 779      * the specified bucket.  It is the responsibility of this
 780      * method to resize the table if appropriate.
 781      *
 782      * Subclass overrides this to alter the behavior of put method.
 783      */
 784     void addEntry(int hash, K key, V value, int bucketIndex) {
 785         if ((size >= threshold) && (null != table[bucketIndex])) {
 786             resize(2 * table.length);
 787             hash = (null != key) ? hash(key) : 0;
 788             bucketIndex = indexFor(hash, table.length);
 789         }
 790 
 791         createEntry(hash, key, value, bucketIndex);
 792     }
 793 
 794     /**
 795      * Like addEntry except that this version is used when creating entries
 796      * as part of Map construction or "pseudo-construction" (cloning,
 797      * deserialization).  This version needn't worry about resizing the table.
 798      *
 799      * Subclass overrides this to alter the behavior of HashMap(Map),
 800      * clone, and readObject.
 801      */
 802     void createEntry(int hash, K key, V value, int bucketIndex) {
 803         @SuppressWarnings("unchecked")
 804             Entry<K,V> e = (Entry<K,V>)table[bucketIndex];
 805         table[bucketIndex] = new Entry<>(hash, key, value, e);
 806         size++;
 807     }
 808 
 809     private abstract class HashIterator<E> implements Iterator<E> {
 810         Entry<?,?> next;        // next entry to return
 811         int expectedModCount;   // For fast-fail
 812         int index;              // current slot
 813         Entry<?,?> current;     // current entry
 814 
 815         HashIterator() {
 816             expectedModCount = modCount;
 817             if (size > 0) { // advance to first entry
 818                 Entry<?,?>[] t = table;
 819                 while (index < t.length && (next = t[index++]) == null)
 820                     ;
 821             }
 822         }
 823 
 824         public final boolean hasNext() {
 825             return next != null;
 826         }
 827 
 828         @SuppressWarnings("unchecked")
 829         final Entry<K,V> nextEntry() {
 830             if (modCount != expectedModCount)
 831                 throw new ConcurrentModificationException();
 832             Entry<?,?> e = next;
 833             if (e == null)
 834                 throw new NoSuchElementException();
 835 
 836             if ((next = e.next) == null) {
 837                 Entry<?,?>[] t = table;
 838                 while (index < t.length && (next = t[index++]) == null)
 839                     ;
 840             }
 841             current = e;
 842             return (Entry<K,V>)e;
 843         }
 844 
 845         public void remove() {
 846             if (current == null)
 847                 throw new IllegalStateException();
 848             if (modCount != expectedModCount)
 849                 throw new ConcurrentModificationException();
 850             Object k = current.key;
 851             current = null;
 852             HashMap.this.removeEntryForKey(k);
 853             expectedModCount = modCount;
 854         }
 855     }
 856 
 857     private final class ValueIterator extends HashIterator<V> {
 858         public V next() {
 859             return nextEntry().value;
 860         }
 861     }
 862 
 863     private final class KeyIterator extends HashIterator<K> {
 864         public K next() {
 865             return nextEntry().getKey();
 866         }
 867     }
 868 
 869     private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
 870         public Map.Entry<K,V> next() {
 871             return nextEntry();
 872         }
 873     }
 874 
 875     // Subclass overrides these to alter behavior of views' iterator() method
 876     Iterator<K> newKeyIterator()   {
 877         return new KeyIterator();
 878     }
 879     Iterator<V> newValueIterator()   {
 880         return new ValueIterator();
 881     }
 882     Iterator<Map.Entry<K,V>> newEntryIterator()   {
 883         return new EntryIterator();
 884     }
 885 
 886 
 887     // Views
 888 
 889     private transient Set<Map.Entry<K,V>> entrySet = null;
 890 
 891     /**
 892      * Returns a {@link Set} view of the keys contained in this map.
 893      * The set is backed by the map, so changes to the map are
 894      * reflected in the set, and vice-versa.  If the map is modified
 895      * while an iteration over the set is in progress (except through
 896      * the iterator's own <tt>remove</tt> operation), the results of
 897      * the iteration are undefined.  The set supports element removal,
 898      * which removes the corresponding mapping from the map, via the
 899      * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
 900      * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
 901      * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
 902      * operations.
 903      */
 904     public Set<K> keySet() {
 905         Set<K> ks = keySet;
 906         return (ks != null ? ks : (keySet = new KeySet()));
 907     }
 908 
 909     private final class KeySet extends AbstractSet<K> {
 910         public Iterator<K> iterator() {
 911             return newKeyIterator();
 912         }
 913         public int size() {
 914             return size;
 915         }
 916         public boolean contains(Object o) {
 917             return containsKey(o);
 918         }
 919         public boolean remove(Object o) {
 920             return HashMap.this.removeEntryForKey(o) != null;
 921         }
 922         public void clear() {
 923             HashMap.this.clear();
 924         }
 925     }
 926 
 927     /**
 928      * Returns a {@link Collection} view of the values contained in this map.
 929      * The collection is backed by the map, so changes to the map are
 930      * reflected in the collection, and vice-versa.  If the map is
 931      * modified while an iteration over the collection is in progress
 932      * (except through the iterator's own <tt>remove</tt> operation),
 933      * the results of the iteration are undefined.  The collection
 934      * supports element removal, which removes the corresponding
 935      * mapping from the map, via the <tt>Iterator.remove</tt>,
 936      * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
 937      * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
 938      * support the <tt>add</tt> or <tt>addAll</tt> operations.
 939      */
 940     public Collection<V> values() {
 941         Collection<V> vs = values;
 942         return (vs != null ? vs : (values = new Values()));
 943     }
 944 
 945     private final class Values extends AbstractCollection<V> {
 946         public Iterator<V> iterator() {
 947             return newValueIterator();
 948         }
 949         public int size() {
 950             return size;
 951         }
 952         public boolean contains(Object o) {
 953             return containsValue(o);
 954         }
 955         public void clear() {
 956             HashMap.this.clear();
 957         }
 958     }
 959 
 960     /**
 961      * Returns a {@link Set} view of the mappings contained in this map.
 962      * The set is backed by the map, so changes to the map are
 963      * reflected in the set, and vice-versa.  If the map is modified
 964      * while an iteration over the set is in progress (except through
 965      * the iterator's own <tt>remove</tt> operation, or through the
 966      * <tt>setValue</tt> operation on a map entry returned by the
 967      * iterator) the results of the iteration are undefined.  The set
 968      * supports element removal, which removes the corresponding
 969      * mapping from the map, via the <tt>Iterator.remove</tt>,
 970      * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
 971      * <tt>clear</tt> operations.  It does not support the
 972      * <tt>add</tt> or <tt>addAll</tt> operations.
 973      *
 974      * @return a set view of the mappings contained in this map
 975      */
 976     public Set<Map.Entry<K,V>> entrySet() {
 977         return entrySet0();
 978     }
 979 
 980     private Set<Map.Entry<K,V>> entrySet0() {
 981         Set<Map.Entry<K,V>> es = entrySet;
 982         return es != null ? es : (entrySet = new EntrySet());
 983     }
 984 
 985     private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
 986         public Iterator<Map.Entry<K,V>> iterator() {
 987             return newEntryIterator();
 988         }
 989         public boolean contains(Object o) {
 990             if (!(o instanceof Map.Entry))
 991                 return false;
 992             Map.Entry<?,?> e = (Map.Entry<?,?>) o;
 993             Entry<K,V> candidate = getEntry(e.getKey());
 994             return candidate != null && candidate.equals(e);
 995         }
 996         public boolean remove(Object o) {
 997             return removeMapping(o) != null;
 998         }
 999         public int size() {
1000             return size;
1001         }
1002         public void clear() {
1003             HashMap.this.clear();
1004         }
1005     }
1006 
1007     /**
1008      * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
1009      * serialize it).
1010      *
1011      * @serialData The <i>capacity</i> of the HashMap (the length of the
1012      *             bucket array) is emitted (int), followed by the
1013      *             <i>size</i> (an int, the number of key-value
1014      *             mappings), followed by the key (Object) and value (Object)
1015      *             for each key-value mapping.  The key-value mappings are
1016      *             emitted in no particular order.
1017      */
1018     private void writeObject(java.io.ObjectOutputStream s)
1019         throws IOException
1020     {
1021         Iterator<Map.Entry<K,V>> i =
1022             (size > 0) ? entrySet0().iterator() : null;
1023 
1024         // Write out the threshold, loadfactor, and any hidden stuff
1025         s.defaultWriteObject();
1026 
1027         // Write out number of buckets
1028         s.writeInt(table.length);
1029 
1030         // Write out size (number of Mappings)
1031         s.writeInt(size);
1032 
1033         // Write out keys and values (alternating)
1034         if (size > 0) {
1035             for(Map.Entry<K,V> e : entrySet0()) {
1036                 s.writeObject(e.getKey());
1037                 s.writeObject(e.getValue());
1038             }
1039         }
1040     }
1041 
1042     private static final long serialVersionUID = 362498820763181265L;
1043 
1044     /**
1045      * Reconstitute the {@code HashMap} instance from a stream (i.e.,
1046      * deserialize it).
1047      */
1048     private void readObject(java.io.ObjectInputStream s)
1049          throws IOException, ClassNotFoundException
1050     {
1051         // Read in the threshold (ignored), loadfactor, and any hidden stuff
1052         s.defaultReadObject();
1053         if (loadFactor <= 0 || Float.isNaN(loadFactor))
1054             throw new InvalidObjectException("Illegal load factor: " +
1055                                                loadFactor);
1056 
1057         // set hashMask
1058         Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
1059                 sun.misc.Hashing.randomHashSeed(this));
1060 
1061         // Read in number of buckets and allocate the bucket array;
1062         s.readInt(); // ignored
1063 
1064         // Read number of mappings
1065         int mappings = s.readInt();
1066         if (mappings < 0)
1067             throw new InvalidObjectException("Illegal mappings count: " +
1068                                                mappings);
1069 
1070         int initialCapacity = (int) Math.min(
1071                 // capacity chosen by number of mappings
1072                 // and desired load (if >= 0.25)
1073                 mappings * Math.min(1 / loadFactor, 4.0f),
1074                 // we have limits...
1075                 HashMap.MAXIMUM_CAPACITY);
1076         int capacity = 1;
1077         // find smallest power of two which holds all mappings
1078         while (capacity < initialCapacity) {
1079             capacity <<= 1;
1080         }
1081 
1082         table = new Entry[capacity];
1083         threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
1084         init();  // Give subclass a chance to do its thing.
1085 
1086 
1087         // Read the keys and values, and put the mappings in the HashMap
1088         for (int i=0; i<mappings; i++) {
1089             @SuppressWarnings("unchecked")
1090                 K key = (K) s.readObject();
1091             @SuppressWarnings("unchecked")
1092                 V value = (V) s.readObject();
1093             putForCreate(key, value);
1094         }
1095     }
1096 
1097     // These methods are used when serializing HashSets
1098     int   capacity()     { return table.length; }
1099     float loadFactor()   { return loadFactor;   }
1100 }