ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/dl/java/util/HashMap.java
Revision: 1.12
Committed: Fri Aug 16 07:20:11 2013 UTC (10 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.11: +1 -1 lines
Log Message:
typo

File Contents

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