ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/HashMap.java
Revision: 1.7
Committed: Fri Aug 10 19:35:20 2018 UTC (5 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.6: +1 -1 lines
Log Message:
8205399: Set node color on pinned HashMap.TreeNode deletion

File Contents

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