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