HashMap.java 110.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26
 */

package java.util;
27

D
duke 已提交
28
import java.io.*;
29 30
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
31
import java.util.concurrent.ThreadLocalRandom;
32 33 34
import java.util.function.Consumer;
import java.util.function.BiFunction;
import java.util.function.Function;
D
duke 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

/**
 * Hash table based implementation of the <tt>Map</tt> interface.  This
 * implementation provides all of the optional map operations, and permits
 * <tt>null</tt> values and the <tt>null</tt> key.  (The <tt>HashMap</tt>
 * class is roughly equivalent to <tt>Hashtable</tt>, except that it is
 * unsynchronized and permits nulls.)  This class makes no guarantees as to
 * the order of the map; in particular, it does not guarantee that the order
 * will remain constant over time.
 *
 * <p>This implementation provides constant-time performance for the basic
 * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
 * disperses the elements properly among the buckets.  Iteration over
 * collection views requires time proportional to the "capacity" of the
 * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
 * of key-value mappings).  Thus, it's very important not to set the initial
 * capacity too high (or the load factor too low) if iteration performance is
 * important.
 *
 * <p>An instance of <tt>HashMap</tt> has two parameters that affect its
 * performance: <i>initial capacity</i> and <i>load factor</i>.  The
 * <i>capacity</i> is the number of buckets in the hash table, and the initial
 * capacity is simply the capacity at the time the hash table is created.  The
 * <i>load factor</i> is a measure of how full the hash table is allowed to
 * get before its capacity is automatically increased.  When the number of
 * entries in the hash table exceeds the product of the load factor and the
 * current capacity, the hash table is <i>rehashed</i> (that is, internal data
 * structures are rebuilt) so that the hash table has approximately twice the
 * number of buckets.
 *
 * <p>As a general rule, the default load factor (.75) offers a good tradeoff
 * between time and space costs.  Higher values decrease the space overhead
 * but increase the lookup cost (reflected in most of the operations of the
 * <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>).  The
 * expected number of entries in the map and its load factor should be taken
 * into account when setting its initial capacity, so as to minimize the
 * number of rehash operations.  If the initial capacity is greater
 * than the maximum number of entries divided by the load factor, no
 * rehash operations will ever occur.
 *
 * <p>If many mappings are to be stored in a <tt>HashMap</tt> instance,
 * creating it with a sufficiently large capacity will allow the mappings to
 * be stored more efficiently than letting it perform automatic rehashing as
 * needed to grow the table.
 *
 * <p><strong>Note that this implementation is not synchronized.</strong>
 * If multiple threads access a hash map concurrently, and at least one of
 * the threads modifies the map structurally, it <i>must</i> be
 * synchronized externally.  (A structural modification is any operation
 * that adds or deletes one or more mappings; merely changing the value
 * associated with a key that an instance already contains is not a
 * structural modification.)  This is typically accomplished by
 * synchronizing on some object that naturally encapsulates the map.
 *
 * If no such object exists, the map should be "wrapped" using the
 * {@link Collections#synchronizedMap Collections.synchronizedMap}
 * method.  This is best done at creation time, to prevent accidental
 * unsynchronized access to the map:<pre>
 *   Map m = Collections.synchronizedMap(new HashMap(...));</pre>
 *
 * <p>The iterators returned by all of this class's "collection view methods"
 * are <i>fail-fast</i>: if the map is structurally modified at any time after
 * the iterator is created, in any way except through the iterator's own
 * <tt>remove</tt> method, the iterator will throw a
 * {@link ConcurrentModificationException}.  Thus, in the face of concurrent
 * modification, the iterator fails quickly and cleanly, rather than risking
 * arbitrary, non-deterministic behavior at an undetermined time in the
 * future.
 *
 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 * as it is, generally speaking, impossible to make any hard guarantees in the
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness: <i>the fail-fast behavior of iterators
 * should be used only to detect bugs.</i>
 *
 * <p>This class is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 *
 * @author  Doug Lea
 * @author  Josh Bloch
 * @author  Arthur van Hoff
 * @author  Neal Gafter
 * @see     Object#hashCode()
 * @see     Collection
 * @see     Map
 * @see     TreeMap
 * @see     Hashtable
 * @since   1.2
 */

public class HashMap<K,V>
132
        extends AbstractMap<K,V>
D
duke 已提交
133 134 135 136 137 138
    implements Map<K,V>, Cloneable, Serializable
{

    /**
     * The default initial capacity - MUST be a power of two.
     */
139
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
D
duke 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

153 154 155
    /**
     * An empty table instance to share when the table is not inflated.
     */
156
    static final Object[] EMPTY_TABLE = {};
157

D
duke 已提交
158 159 160
    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
161
    transient Object[] table = EMPTY_TABLE;
D
duke 已提交
162 163 164 165 166 167 168 169 170 171

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     * The next size value at which to resize (capacity * load factor).
     * @serial
     */
172 173
    // If table == EMPTY_TABLE then this is the initial capacity at which the
    // table will be created when inflated.
D
duke 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    int threshold;

    /**
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
190
    transient int modCount;
D
duke 已提交
191

192 193 194
    /**
     * Holds values which can't be initialized until after VM is booted.
     */
195 196 197 198 199 200 201 202 203
    private static class Holder {
        static final sun.misc.Unsafe UNSAFE;

        /**
         * Offset of "final" hashSeed field we must set in
         * readObject() method.
         */
        static final long HASHSEED_OFFSET;

204 205
        static final boolean USE_HASHSEED;

206
        static {
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
            String hashSeedProp = java.security.AccessController.doPrivileged(
                    new sun.security.action.GetPropertyAction(
                        "jdk.map.useRandomSeed"));
            boolean localBool = (null != hashSeedProp)
                    ? Boolean.parseBoolean(hashSeedProp) : false;
            USE_HASHSEED = localBool;

            if (USE_HASHSEED) {
                try {
                    UNSAFE = sun.misc.Unsafe.getUnsafe();
                    HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
                        HashMap.class.getDeclaredField("hashSeed"));
                } catch (NoSuchFieldException | SecurityException e) {
                    throw new InternalError("Failed to record hashSeed offset", e);
                }
            } else {
                UNSAFE = null;
                HASHSEED_OFFSET = 0;
225 226 227 228
            }
        }
    }

229
    /*
230 231
     * A randomizing value associated with this instance that is applied to
     * hash code of keys to make hash collisions harder to find.
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
     *
     * Non-final so it can be set lazily, but be sure not to set more than once.
     */
    transient final int hashSeed;

    /*
     * TreeBin/TreeNode code from CHM doesn't handle the null key.  Store the
     * null key entry here.
     */
    transient Entry<K,V> nullKeyEntry = null;

    /*
     * In order to improve performance under high hash-collision conditions,
     * HashMap will switch to storing a bin's entries in a balanced tree
     * (TreeBin) instead of a linked-list once the number of entries in the bin
     * passes a certain threshold (TreeBin.TREE_THRESHOLD), if at least one of
     * the keys in the bin implements Comparable.  This technique is borrowed
     * from ConcurrentHashMap.
     */

    /*
     * Code based on CHMv8
     *
     * Node type for TreeBin
     */
    final static class TreeNode<K,V> {
        TreeNode parent;  // red-black tree links
        TreeNode left;
        TreeNode right;
        TreeNode prev;    // needed to unlink next upon deletion
        boolean red;
        final HashMap.Entry<K,V> entry;

        TreeNode(HashMap.Entry<K,V> entry, Object next, TreeNode parent) {
            this.entry = entry;
            this.entry.next = next;
            this.parent = parent;
        }
    }

    /**
     * Returns a Class for the given object of the form "class C
     * implements Comparable<C>", if one exists, else null.  See the TreeBin
     * docs, below, for explanation.
     */
    static Class<?> comparableClassFor(Object x) {
        Class<?> c, s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
        if ((c = x.getClass()) == String.class) // bypass checks
            return c;
        if ((cmpc = Comparable.class).isAssignableFrom(c)) {
            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
                c = s; // find topmost comparable class
            if ((ts  = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    /*
     * Code based on CHMv8
     *
     * A specialized form of red-black tree for use in bins
     * whose size exceeds a threshold.
     *
     * TreeBins use a special form of comparison for search and
     * related operations (which is the main reason we cannot use
     * existing collections such as TreeMaps). TreeBins contain
     * Comparable elements, but may contain others, as well as
     * elements that are Comparable but not necessarily Comparable<T>
     * for the same T, so we cannot invoke compareTo among them. To
     * handle this, the tree is ordered primarily by hash value, then
     * by Comparable.compareTo order if applicable.  On lookup at a
     * node, if elements are not comparable or compare as 0 then both
     * left and right children may need to be searched in the case of
     * tied hash values. (This corresponds to the full list search
     * that would be necessary if all elements were non-Comparable and
     * had tied hashes.)  The red-black balancing code is updated from
     * pre-jdk-collections
     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
     * Algorithms" (CLR).
320
     */
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    final class TreeBin {
        /*
         * The bin count threshold for using a tree rather than list for a bin. The
         * value reflects the approximate break-even point for using tree-based
         * operations.
         */
        static final int TREE_THRESHOLD = 16;

        TreeNode<K,V> root;  // root of tree
        TreeNode<K,V> first; // head of next-pointer list

        /*
         * Split a TreeBin into lo and hi parts and install in given table.
         *
         * Existing Entrys are re-used, which maintains the before/after links for
         * LinkedHashMap.Entry.
         *
         * No check for Comparable, though this is the same as CHM.
         */
        final void splitTreeBin(Object[] newTable, int i, TreeBin loTree, TreeBin hiTree) {
            TreeBin oldTree = this;
            int bit = newTable.length >>> 1;
            int loCount = 0, hiCount = 0;
            TreeNode<K,V> e = oldTree.first;
            TreeNode<K,V> next;

            // This method is called when the table has just increased capacity,
            // so indexFor() is now taking one additional bit of hash into
            // account ("bit").  Entries in this TreeBin now belong in one of
            // two bins, "i" or "i+bit", depending on if the new top bit of the
            // hash is set.  The trees for the two bins are loTree and hiTree.
            // If either tree ends up containing fewer than TREE_THRESHOLD
            // entries, it is converted back to a linked list.
            while (e != null) {
                // Save entry.next - it will get overwritten in putTreeNode()
                next = (TreeNode<K,V>)e.entry.next;

                int h = e.entry.hash;
                K k = (K) e.entry.key;
                V v = e.entry.value;
                if ((h & bit) == 0) {
                    ++loCount;
                    // Re-using e.entry
                    loTree.putTreeNode(h, k, v, e.entry);
                } else {
                    ++hiCount;
                    hiTree.putTreeNode(h, k, v, e.entry);
                }
                // Iterate using the saved 'next'
                e = next;
            }
            if (loCount < TREE_THRESHOLD) { // too small, convert back to list
                HashMap.Entry loEntry = null;
                TreeNode<K,V> p = loTree.first;
                while (p != null) {
                    @SuppressWarnings("unchecked")
                    TreeNode<K,V> savedNext = (TreeNode<K,V>) p.entry.next;
                    p.entry.next = loEntry;
                    loEntry = p.entry;
                    p = savedNext;
                }
                // assert newTable[i] == null;
                newTable[i] = loEntry;
            } else {
                // assert newTable[i] == null;
                newTable[i] = loTree;
            }
            if (hiCount < TREE_THRESHOLD) { // too small, convert back to list
                HashMap.Entry hiEntry = null;
                TreeNode<K,V> p = hiTree.first;
                while (p != null) {
                    @SuppressWarnings("unchecked")
                    TreeNode<K,V> savedNext = (TreeNode<K,V>) p.entry.next;
                    p.entry.next = hiEntry;
                    hiEntry = p.entry;
                    p = savedNext;
                }
                // assert newTable[i + bit] == null;
                newTable[i + bit] = hiEntry;
            } else {
                // assert newTable[i + bit] == null;
                newTable[i + bit] = hiTree;
            }
        }

        /*
         * Popuplate the TreeBin with entries from the linked list e
         *
         * Assumes 'this' is a new/empty TreeBin
         *
         * Note: no check for Comparable
         * Note: I believe this changes iteration order
         */
        @SuppressWarnings("unchecked")
        void populate(HashMap.Entry e) {
            // assert root == null;
            // assert first == null;
            HashMap.Entry next;
            while (e != null) {
                // Save entry.next - it will get overwritten in putTreeNode()
                next = (HashMap.Entry)e.next;
                // Re-using Entry e will maintain before/after in LinkedHM
                putTreeNode(e.hash, (K)e.key, (V)e.value, e);
                // Iterate using the saved 'next'
                e = next;
            }
        }

        /**
         * Copied from CHMv8
         * From CLR
         */
        private void rotateLeft(TreeNode p) {
            if (p != null) {
                TreeNode r = p.right, pp, rl;
                if ((rl = p.right = r.left) != null) {
                    rl.parent = p;
                }
                if ((pp = r.parent = p.parent) == null) {
                    root = r;
                } else if (pp.left == p) {
                    pp.left = r;
                } else {
                    pp.right = r;
                }
                r.left = p;
                p.parent = r;
            }
        }

        /**
         * Copied from CHMv8
         * From CLR
         */
        private void rotateRight(TreeNode p) {
            if (p != null) {
                TreeNode l = p.left, pp, lr;
                if ((lr = p.left = l.right) != null) {
                    lr.parent = p;
                }
                if ((pp = l.parent = p.parent) == null) {
                    root = l;
                } else if (pp.right == p) {
                    pp.right = l;
                } else {
                    pp.left = l;
                }
                l.right = p;
                p.parent = l;
            }
        }

        /**
         * Returns the TreeNode (or null if not found) for the given
         * key.  A front-end for recursive version.
         */
        final TreeNode getTreeNode(int h, K k) {
            return getTreeNode(h, k, root, comparableClassFor(k));
        }

        /**
         * Returns the TreeNode (or null if not found) for the given key
         * starting at given root.
         */
        @SuppressWarnings("unchecked")
        final TreeNode getTreeNode (int h, K k, TreeNode p, Class<?> cc) {
            // assert k != null;
            while (p != null) {
                int dir, ph;  Object pk;
                if ((ph = p.entry.hash) != h)
                    dir = (h < ph) ? -1 : 1;
                else if ((pk = p.entry.key) == k || k.equals(pk))
                    return p;
                else if (cc == null || comparableClassFor(pk) != cc ||
                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
                    // assert pk != null;
                    TreeNode r, pl, pr; // check both sides
                    if ((pr = p.right) != null &&
                        (r = getTreeNode(h, k, pr, cc)) != null)
                        return r;
                    else if ((pl = p.left) != null)
                        dir = -1;
                    else // nothing there
                        break;
                }
                p = (dir > 0) ? p.right : p.left;
            }
            return null;
        }

        /*
         * Finds or adds a node.
         *
         * 'entry' should be used to recycle an existing Entry (e.g. in the case
         * of converting a linked-list bin to a TreeBin).
         * If entry is null, a new Entry will be created for the new TreeNode
         *
         * @return the TreeNode containing the mapping, or null if a new
         * TreeNode was added
         */
        @SuppressWarnings("unchecked")
        TreeNode putTreeNode(int h, K k, V v, HashMap.Entry<K,V> entry) {
            // assert k != null;
            //if (entry != null) {
                // assert h == entry.hash;
                // assert k == entry.key;
                // assert v == entry.value;
            // }
            Class<?> cc = comparableClassFor(k);
            TreeNode pp = root, p = null;
            int dir = 0;
            while (pp != null) { // find existing node or leaf to insert at
                int ph;  Object pk;
                p = pp;
                if ((ph = p.entry.hash) != h)
                    dir = (h < ph) ? -1 : 1;
                else if ((pk = p.entry.key) == k || k.equals(pk))
                    return p;
                else if (cc == null || comparableClassFor(pk) != cc ||
                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
                    TreeNode r, pr;
                    if ((pr = p.right) != null &&
                        (r = getTreeNode(h, k, pr, cc)) != null)
                        return r;
                    else // continue left
                        dir = -1;
                }
                pp = (dir > 0) ? p.right : p.left;
            }

            // Didn't find the mapping in the tree, so add it
            TreeNode f = first;
            TreeNode x;
            if (entry != null) {
                x = new TreeNode(entry, f, p);
            } else {
                x = new TreeNode(newEntry(h, k, v, null), f, p);
            }
            first = x;

            if (p == null) {
                root = x;
            } else { // attach and rebalance; adapted from CLR
                TreeNode xp, xpp;
                if (f != null) {
                    f.prev = x;
                }
                if (dir <= 0) {
                    p.left = x;
                } else {
                    p.right = x;
                }
                x.red = true;
                while (x != null && (xp = x.parent) != null && xp.red
                        && (xpp = xp.parent) != null) {
                    TreeNode xppl = xpp.left;
                    if (xp == xppl) {
                        TreeNode y = xpp.right;
                        if (y != null && y.red) {
                            y.red = false;
                            xp.red = false;
                            xpp.red = true;
                            x = xpp;
                        } else {
                            if (x == xp.right) {
                                rotateLeft(x = xp);
                                xpp = (xp = x.parent) == null ? null : xp.parent;
                            }
                            if (xp != null) {
                                xp.red = false;
                                if (xpp != null) {
                                    xpp.red = true;
                                    rotateRight(xpp);
                                }
                            }
                        }
                    } else {
                        TreeNode y = xppl;
                        if (y != null && y.red) {
                            y.red = false;
                            xp.red = false;
                            xpp.red = true;
                            x = xpp;
                        } else {
                            if (x == xp.left) {
                                rotateRight(x = xp);
                                xpp = (xp = x.parent) == null ? null : xp.parent;
                            }
                            if (xp != null) {
                                xp.red = false;
                                if (xpp != null) {
                                    xpp.red = true;
                                    rotateLeft(xpp);
                                }
                            }
                        }
                    }
                }
                TreeNode r = root;
                if (r != null && r.red) {
                    r.red = false;
                }
            }
            return null;
        }

        /*
         * From CHMv8
         *
         * Removes the given node, that must be present before this
         * call.  This is messier than typical red-black deletion code
         * because we cannot swap the contents of an interior node
         * with a leaf successor that is pinned by "next" pointers
         * that are accessible independently of lock. So instead we
         * swap the tree linkages.
         */
        final void deleteTreeNode(TreeNode p) {
            TreeNode next = (TreeNode) p.entry.next; // unlink traversal pointers
            TreeNode pred = p.prev;
            if (pred == null) {
                first = next;
            } else {
                pred.entry.next = next;
            }
            if (next != null) {
                next.prev = pred;
            }
            TreeNode replacement;
            TreeNode pl = p.left;
            TreeNode pr = p.right;
            if (pl != null && pr != null) {
                TreeNode s = pr, sl;
                while ((sl = s.left) != null) // find successor
                {
                    s = sl;
                }
                boolean c = s.red;
                s.red = p.red;
                p.red = c; // swap colors
                TreeNode sr = s.right;
                TreeNode pp = p.parent;
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                } else {
                    TreeNode sp = s.parent;
                    if ((p.parent = sp) != null) {
                        if (s == sp.left) {
                            sp.left = p;
                        } else {
                            sp.right = p;
                        }
                    }
                    if ((s.right = pr) != null) {
                        pr.parent = s;
                    }
                }
                p.left = null;
                if ((p.right = sr) != null) {
                    sr.parent = p;
                }
                if ((s.left = pl) != null) {
                    pl.parent = s;
                }
                if ((s.parent = pp) == null) {
                    root = s;
                } else if (p == pp.left) {
                    pp.left = s;
                } else {
                    pp.right = s;
                }
                replacement = sr;
            } else {
                replacement = (pl != null) ? pl : pr;
            }
            TreeNode pp = p.parent;
            if (replacement == null) {
                if (pp == null) {
                    root = null;
                    return;
                }
                replacement = p;
            } else {
                replacement.parent = pp;
                if (pp == null) {
                    root = replacement;
                } else if (p == pp.left) {
                    pp.left = replacement;
                } else {
                    pp.right = replacement;
                }
                p.left = p.right = p.parent = null;
            }
            if (!p.red) { // rebalance, from CLR
                TreeNode x = replacement;
                while (x != null) {
                    TreeNode xp, xpl;
                    if (x.red || (xp = x.parent) == null) {
                        x.red = false;
                        break;
                    }
                    if (x == (xpl = xp.left)) {
                        TreeNode sib = xp.right;
                        if (sib != null && sib.red) {
                            sib.red = false;
                            xp.red = true;
                            rotateLeft(xp);
                            sib = (xp = x.parent) == null ? null : xp.right;
                        }
                        if (sib == null) {
                            x = xp;
                        } else {
                            TreeNode sl = sib.left, sr = sib.right;
                            if ((sr == null || !sr.red)
                                    && (sl == null || !sl.red)) {
                                sib.red = true;
                                x = xp;
                            } else {
                                if (sr == null || !sr.red) {
                                    if (sl != null) {
                                        sl.red = false;
                                    }
                                    sib.red = true;
                                    rotateRight(sib);
                                    sib = (xp = x.parent) == null ?
                                        null : xp.right;
                                }
                                if (sib != null) {
                                    sib.red = (xp == null) ? false : xp.red;
                                    if ((sr = sib.right) != null) {
                                        sr.red = false;
                                    }
                                }
                                if (xp != null) {
                                    xp.red = false;
                                    rotateLeft(xp);
                                }
                                x = root;
                            }
                        }
                    } else { // symmetric
                        TreeNode sib = xpl;
                        if (sib != null && sib.red) {
                            sib.red = false;
                            xp.red = true;
                            rotateRight(xp);
                            sib = (xp = x.parent) == null ? null : xp.left;
                        }
                        if (sib == null) {
                            x = xp;
                        } else {
                            TreeNode sl = sib.left, sr = sib.right;
                            if ((sl == null || !sl.red)
                                    && (sr == null || !sr.red)) {
                                sib.red = true;
                                x = xp;
                            } else {
                                if (sl == null || !sl.red) {
                                    if (sr != null) {
                                        sr.red = false;
                                    }
                                    sib.red = true;
                                    rotateLeft(sib);
                                    sib = (xp = x.parent) == null ?
                                        null : xp.left;
                                }
                                if (sib != null) {
                                    sib.red = (xp == null) ? false : xp.red;
                                    if ((sl = sib.left) != null) {
                                        sl.red = false;
                                    }
                                }
                                if (xp != null) {
                                    xp.red = false;
                                    rotateRight(xp);
                                }
                                x = root;
                            }
                        }
                    }
                }
            }
            if (p == replacement && (pp = p.parent) != null) {
                if (p == pp.left) // detach pointers
                {
                    pp.left = null;
                } else if (p == pp.right) {
                    pp.right = null;
                }
                p.parent = null;
            }
        }
    }
814

D
duke 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
834
        threshold = initialCapacity;
835
        hashSeed = initHashSeed();
D
duke 已提交
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
        init();
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
855
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
D
duke 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868
    }

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
869
                DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
870 871
        inflateTable(threshold);

D
duke 已提交
872
        putAllForCreate(m);
873
        // assert size == m.size();
D
duke 已提交
874 875
    }

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    private static int roundUpToPowerOf2(int number) {
        // assert number >= 0 : "number must be non-negative";
        int rounded = number >= MAXIMUM_CAPACITY
                ? MAXIMUM_CAPACITY
                : (rounded = Integer.highestOneBit(number)) != 0
                    ? (Integer.bitCount(number) > 1) ? rounded << 1 : rounded
                    : 1;

        return rounded;
    }

    /**
     * Inflates the table.
     */
    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
895
        table = new Object[capacity];
896 897
    }

D
duke 已提交
898 899 900 901 902 903 904 905 906 907 908 909
    // internal utilities

    /**
     * Initialization hook for subclasses. This method is called
     * in all constructors and pseudo-constructors (clone, readObject)
     * after HashMap has been initialized but before any entries have
     * been inserted.  (In the absence of this method, readObject would
     * require explicit knowledge of subclasses.)
     */
    void init() {
    }

910 911 912 913 914 915
    /**
     * Return an initial value for the hashSeed, or 0 if the random seed is not
     * enabled.
     */
    final int initHashSeed() {
        if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
916 917
            int seed = ThreadLocalRandom.current().nextInt();
            return (seed != 0) ? seed : 1;
918 919 920 921
        }
        return 0;
    }

D
duke 已提交
922
    /**
923
     * Retrieve object hash code and applies a supplemental hash function to the
924
     * result hash, which defends against poor quality hash functions. This is
925
     * critical because HashMap uses power-of-two length hash tables, that
D
duke 已提交
926
     * otherwise encounter collisions for hashCodes that do not differ
927
     * in lower bits.
D
duke 已提交
928
     */
929
    final int hash(Object k) {
930
        int  h = hashSeed ^ k.hashCode();
931

D
duke 已提交
932 933 934 935 936 937 938 939 940 941 942
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

    /**
     * Returns index for hash code h.
     */
    static int indexFor(int h, int length) {
943
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
D
duke 已提交
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
        return h & (length-1);
    }

    /**
     * Returns the number of key-value mappings in this map.
     *
     * @return the number of key-value mappings in this map
     */
    public int size() {
        return size;
    }

    /**
     * Returns <tt>true</tt> if this map contains no key-value mappings.
     *
     * @return <tt>true</tt> if this map contains no key-value mappings
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
982
    @SuppressWarnings("unchecked")
D
duke 已提交
983
    public V get(Object key) {
984
        Entry<K,V> entry = getEntry(key);
D
duke 已提交
985

986
        return null == entry ? null : entry.getValue();
D
duke 已提交
987 988
    }

989 990 991 992 993 994 995
    @Override
    public V getOrDefault(Object key, V defaultValue) {
        Entry<K,V> entry = getEntry(key);

        return (entry == null) ? defaultValue : entry.getValue();
    }

D
duke 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }

    /**
     * Returns the entry associated with the specified key in the
     * HashMap.  Returns null if the HashMap contains no mapping
     * for the key.
     */
1013
    @SuppressWarnings("unchecked")
D
duke 已提交
1014
    final Entry<K,V> getEntry(Object key) {
1015 1016 1017
        if (isEmpty()) {
            return null;
        }
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
        if (key == null) {
            return nullKeyEntry;
        }
        int hash = hash(key);
        int bin = indexFor(hash, table.length);

        if (table[bin] instanceof Entry) {
            Entry<K,V> e = (Entry<K,V>) table[bin];
            for (; e != null; e = (Entry<K,V>)e.next) {
                Object k;
                if (e.hash == hash &&
                    ((k = e.key) == key || key.equals(k))) {
                    return e;
                }
            }
        } else if (table[bin] != null) {
            TreeBin e = (TreeBin)table[bin];
            TreeNode p = e.getTreeNode(hash, (K)key);
            if (p != null) {
                // assert p.entry.hash == hash && p.entry.key.equals(key);
                return (Entry<K,V>)p.entry;
            } else {
                return null;
            }
D
duke 已提交
1042 1043 1044 1045
        }
        return null;
    }

1046

D
duke 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
1059
    @SuppressWarnings("unchecked")
D
duke 已提交
1060
    public V put(K key, V value) {
1061 1062 1063
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1064
       if (key == null)
D
duke 已提交
1065
            return putForNullKey(value);
1066
        int hash = hash(key);
D
duke 已提交
1067
        int i = indexFor(hash, table.length);
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?

        if (table[i] instanceof Entry) {
            // Bin contains ordinary Entries.  Search for key in the linked list
            // of entries, counting the number of entries.  Only check for
            // TreeBin conversion if the list size is >= TREE_THRESHOLD.
            // (The conversion still may not happen if the table gets resized.)
            int listSize = 0;
            Entry<K,V> e = (Entry<K,V>) table[i];
            for (; e != null; e = (Entry<K,V>)e.next) {
                Object k;
                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                    V oldValue = e.value;
                    e.value = value;
                    e.recordAccess(this);
                    return oldValue;
                }
                listSize++;
            }
            // Didn't find, so fall through and call addEntry() to add the
            // Entry and check for TreeBin conversion.
            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
        } else if (table[i] != null) {
            TreeBin e = (TreeBin)table[i];
            TreeNode p = e.putTreeNode(hash, key, value, null);
            if (p == null) { // putTreeNode() added a new node
                modCount++;
                size++;
                if (size >= threshold) {
                    resize(2 * table.length);
                }
                return null;
            } else { // putTreeNode() found an existing node
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                V oldVal = pEntry.value;
                pEntry.value = value;
                pEntry.recordAccess(this);
                return oldVal;
D
duke 已提交
1106 1107 1108
            }
        }
        modCount++;
1109
        addEntry(hash, key, value, i, checkIfNeedTree);
D
duke 已提交
1110 1111 1112 1113 1114 1115 1116
        return null;
    }

    /**
     * Offloaded version of put for null keys
     */
    private V putForNullKey(V value) {
1117 1118 1119 1120 1121
        if (nullKeyEntry != null) {
            V oldValue = nullKeyEntry.value;
            nullKeyEntry.value = value;
            nullKeyEntry.recordAccess(this);
            return oldValue;
D
duke 已提交
1122 1123
        }
        modCount++;
1124 1125
        size++; // newEntry() skips size++
        nullKeyEntry = newEntry(0, null, value, null);
D
duke 已提交
1126 1127 1128
        return null;
    }

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    private void putForCreateNullKey(V value) {
        // Look for preexisting entry for key.  This will never happen for
        // clone or deserialize.  It will only happen for construction if the
        // input Map is a sorted map whose ordering is inconsistent w/ equals.
        if (nullKeyEntry != null) {
            nullKeyEntry.value = value;
        } else {
            nullKeyEntry = newEntry(0, null, value, null);
            size++;
        }
    }


D
duke 已提交
1142 1143 1144
    /**
     * This method is used instead of put by constructors and
     * pseudoconstructors (clone, readObject).  It does not resize the table,
1145 1146
     * check for comodification, etc, though it will convert bins to TreeBins
     * as needed.  It calls createEntry rather than addEntry.
D
duke 已提交
1147
     */
1148
    @SuppressWarnings("unchecked")
D
duke 已提交
1149
    private void putForCreate(K key, V value) {
1150 1151 1152 1153 1154
        if (null == key) {
            putForCreateNullKey(value);
            return;
        }
        int hash = hash(key);
D
duke 已提交
1155
        int i = indexFor(hash, table.length);
1156
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
D
duke 已提交
1157 1158 1159 1160 1161 1162

        /**
         * Look for preexisting entry for key.  This will never happen for
         * clone or deserialize.  It will only happen for construction if the
         * input Map is a sorted map whose ordering is inconsistent w/ equals.
         */
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        if (table[i] instanceof Entry) {
            int listSize = 0;
            Entry<K,V> e = (Entry<K,V>) table[i];
            for (; e != null; e = (Entry<K,V>)e.next) {
                Object k;
                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                    e.value = value;
                    return;
                }
                listSize++;
D
duke 已提交
1173
            }
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
            // Didn't find, fall through to createEntry().
            // Check for conversion to TreeBin done via createEntry().
            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
        } else if (table[i] != null) {
            TreeBin e = (TreeBin)table[i];
            TreeNode p = e.putTreeNode(hash, key, value, null);
            if (p != null) {
                p.entry.setValue(value); // Found an existing node, set value
            } else {
                size++; // Added a new TreeNode, so update size
            }
            // don't need modCount++/check for resize - just return
            return;
D
duke 已提交
1187 1188
        }

1189
        createEntry(hash, key, value, i, checkIfNeedTree);
D
duke 已提交
1190 1191 1192
    }

    private void putAllForCreate(Map<? extends K, ? extends V> m) {
D
dl 已提交
1193
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
D
duke 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
            putForCreate(e.getKey(), e.getValue());
    }

    /**
     * Rehashes the contents of this map into a new array with a
     * larger capacity.  This method is called automatically when the
     * number of keys in this map reaches its threshold.
     *
     * If current capacity is MAXIMUM_CAPACITY, this method does not
     * resize the map, but sets threshold to Integer.MAX_VALUE.
     * This has the effect of preventing future calls.
     *
     * @param newCapacity the new capacity, MUST be a power of two;
     *        must be greater than current capacity unless current
     *        capacity is MAXIMUM_CAPACITY (in which case value
     *        is irrelevant).
     */
    void resize(int newCapacity) {
1212
        Object[] oldTable = table;
D
duke 已提交
1213 1214 1215 1216 1217 1218
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

1219
        Object[] newTable = new Object[newCapacity];
D
duke 已提交
1220 1221
        transfer(newTable);
        table = newTable;
1222
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
D
duke 已提交
1223 1224 1225 1226
    }

    /**
     * Transfers all entries from current table to newTable.
1227 1228
     *
     * Assumes newTable is larger than table
D
duke 已提交
1229
     */
1230
    @SuppressWarnings("unchecked")
1231 1232 1233 1234
    void transfer(Object[] newTable) {
        Object[] src = table;
        // assert newTable.length > src.length : "newTable.length(" +
        //   newTable.length + ") expected to be > src.length("+src.length+")";
D
duke 已提交
1235
        int newCapacity = newTable.length;
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
        for (int j = 0; j < src.length; j++) {
             if (src[j] instanceof Entry) {
                // Assume: since wasn't TreeBin before, won't need TreeBin now
                Entry<K,V> e = (Entry<K,V>) src[j];
                while (null != e) {
                    Entry<K,V> next = (Entry<K,V>)e.next;
                    int i = indexFor(e.hash, newCapacity);
                    e.next = (Entry<K,V>) newTable[i];
                    newTable[i] = e;
                    e = next;
                }
            } else if (src[j] != null) {
                TreeBin e = (TreeBin) src[j];
                TreeBin loTree = new TreeBin();
                TreeBin hiTree = new TreeBin();
                e.splitTreeBin(newTable, j, loTree, hiTree);
D
duke 已提交
1252 1253
            }
        }
1254
        Arrays.fill(table, null);
D
duke 已提交
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    }

    /**
     * Copies all of the mappings from the specified map to this map.
     * These mappings will replace any mappings that this map had for
     * any of the keys currently in the specified map.
     *
     * @param m mappings to be stored in this map
     * @throws NullPointerException if the specified map is null
     */
    public void putAll(Map<? extends K, ? extends V> m) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded == 0)
            return;

1270 1271 1272 1273
        if (table == EMPTY_TABLE) {
            inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
        }

D
duke 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282
        /*
         * Expand the map if the map if the number of mappings to be added
         * is greater than or equal to threshold.  This is conservative; the
         * obvious condition is (m.size() + size) >= threshold, but this
         * condition could result in a map with twice the appropriate capacity,
         * if the keys to be added overlap with the keys already in this map.
         * By using the conservative calculation, we subject ourself
         * to at most one extra resize.
         */
1283 1284
        if (numKeysToBeAdded > threshold && table.length < MAXIMUM_CAPACITY) {
            resize(table.length * 2);
D
duke 已提交
1285 1286
        }

D
dl 已提交
1287
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
D
duke 已提交
1288
            put(e.getKey(), e.getValue());
1289
        }
D
duke 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304

    /**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

1305 1306 1307 1308 1309 1310 1311
    // optimized implementations of default methods in Map

    @Override
    public V putIfAbsent(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1312 1313 1314 1315 1316 1317 1318 1319 1320
        if (key == null) {
            if (nullKeyEntry == null || nullKeyEntry.value == null) {
                putForNullKey(value);
                return null;
            } else {
                return nullKeyEntry.value;
            }
        }
        int hash = hash(key);
1321
        int i = indexFor(hash, table.length);
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?

        if (table[i] instanceof Entry) {
            int listSize = 0;
            Entry<K,V> e = (Entry<K,V>) table[i];
            for (; e != null; e = (Entry<K,V>)e.next) {
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    if (e.value != null) {
                        return e.value;
                    }
                    e.value = value;
                    e.recordAccess(this);
                    return null;
1335
                }
1336 1337 1338 1339 1340 1341 1342 1343 1344
                listSize++;
            }
            // Didn't find, so fall through and call addEntry() to add the
            // Entry and check for TreeBin conversion.
            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
        } else if (table[i] != null) {
            TreeBin e = (TreeBin)table[i];
            TreeNode p = e.putTreeNode(hash, key, value, null);
            if (p == null) { // not found, putTreeNode() added a new node
1345
                modCount++;
1346 1347 1348 1349
                size++;
                if (size >= threshold) {
                    resize(2 * table.length);
                }
1350
                return null;
1351 1352 1353 1354 1355 1356 1357 1358
            } else { // putTreeNode() found an existing node
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                V oldVal = pEntry.value;
                if (oldVal == null) { // only replace if maps to null
                    pEntry.value = value;
                    pEntry.recordAccess(this);
                }
                return oldVal;
1359 1360 1361
            }
        }
        modCount++;
1362
        addEntry(hash, key, value, i, checkIfNeedTree);
1363 1364 1365 1366 1367 1368 1369 1370
        return null;
    }

    @Override
    public boolean remove(Object key, Object value) {
        if (isEmpty()) {
            return false;
        }
1371 1372 1373 1374 1375 1376 1377 1378 1379
        if (key == null) {
            if (nullKeyEntry != null &&
                 Objects.equals(nullKeyEntry.value, value)) {
                removeNullKey();
                return true;
            }
            return false;
        }
        int hash = hash(key);
1380 1381
        int i = indexFor(hash, table.length);

1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
        if (table[i] instanceof Entry) {
            @SuppressWarnings("unchecked")
            Entry<K,V> prev = (Entry<K,V>) table[i];
            Entry<K,V> e = prev;
            while (e != null) {
                @SuppressWarnings("unchecked")
                Entry<K,V> next = (Entry<K,V>) e.next;
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    if (!Objects.equals(e.value, value)) {
                        return false;
                    }
                    modCount++;
                    size--;
                    if (prev == e)
                        table[i] = next;
                    else
                        prev.next = next;
                    e.recordRemoval(this);
                    return true;
                }
                prev = e;
                e = next;
            }
        } else if (table[i] != null) {
            TreeBin tb = ((TreeBin) table[i]);
            TreeNode p = tb.getTreeNode(hash, (K)key);
            if (p != null) {
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                // assert pEntry.key.equals(key);
                if (Objects.equals(pEntry.value, value)) {
                    modCount++;
                    size--;
                    tb.deleteTreeNode(p);
                    pEntry.recordRemoval(this);
                    if (tb.root == null || tb.first == null) {
                        // assert tb.root == null && tb.first == null :
                        //         "TreeBin.first and root should both be null";
                        // TreeBin is now empty, we should blank this bin
                        table[i] = null;
                    }
                    return true;
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
                }
            }
        }
        return false;
    }

    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        if (isEmpty()) {
            return false;
        }
1434 1435 1436 1437
        if (key == null) {
            if (nullKeyEntry != null &&
                 Objects.equals(nullKeyEntry.value, oldValue)) {
                putForNullKey(newValue);
1438 1439
                return true;
            }
1440
            return false;
1441
        }
1442 1443
        int hash = hash(key);
        int i = indexFor(hash, table.length);
1444

1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
        if (table[i] instanceof Entry) {
            @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>) table[i];
            for (; e != null; e = (Entry<K,V>)e.next) {
                if (e.hash == hash && Objects.equals(e.key, key) && Objects.equals(e.value, oldValue)) {
                    e.value = newValue;
                    e.recordAccess(this);
                    return true;
                }
            }
            return false;
        } else if (table[i] != null) {
            TreeBin tb = ((TreeBin) table[i]);
            TreeNode p = tb.getTreeNode(hash, key);
            if (p != null) {
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                // assert pEntry.key.equals(key);
                if (Objects.equals(pEntry.value, oldValue)) {
                    pEntry.value = newValue;
                    pEntry.recordAccess(this);
                    return true;
                }
            }
        }
1469 1470 1471
        return false;
    }

1472
   @Override
1473 1474 1475 1476
    public V replace(K key, V value) {
        if (isEmpty()) {
            return null;
        }
1477 1478 1479 1480 1481 1482 1483
        if (key == null) {
            if (nullKeyEntry != null) {
                return putForNullKey(value);
            }
            return null;
        }
        int hash = hash(key);
1484
        int i = indexFor(hash, table.length);
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
        if (table[i] instanceof Entry) {
            @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>)table[i];
            for (; e != null; e = (Entry<K,V>)e.next) {
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    V oldValue = e.value;
                    e.value = value;
                    e.recordAccess(this);
                    return oldValue;
                }
            }

            return null;
        } else if (table[i] != null) {
            TreeBin tb = ((TreeBin) table[i]);
            TreeNode p = tb.getTreeNode(hash, key);
            if (p != null) {
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                // assert pEntry.key.equals(key);
                V oldValue = pEntry.value;
                pEntry.value = value;
                pEntry.recordAccess(this);
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
                return oldValue;
            }
        }
        return null;
    }

    @Override
    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1518 1519 1520 1521 1522 1523 1524
        if (key == null) {
            if (nullKeyEntry == null || nullKeyEntry.value == null) {
                V newValue = mappingFunction.apply(key);
                if (newValue != null) {
                    putForNullKey(newValue);
                }
                return newValue;
1525
            }
1526
            return nullKeyEntry.value;
1527
        }
1528 1529 1530
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
1531

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        if (table[i] instanceof Entry) {
            int listSize = 0;
            @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>)table[i];
            for (; e != null; e = (Entry<K,V>)e.next) {
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    V oldValue = e.value;
                    if (oldValue == null) {
                        V newValue = mappingFunction.apply(key);
                        if (newValue != null) {
                            e.value = newValue;
                            e.recordAccess(this);
                        }
                        return newValue;
                    }
                    return oldValue;
                }
                listSize++;
            }
            // Didn't find, fall through to call the mapping function
            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
        } else if (table[i] != null) {
            TreeBin e = (TreeBin)table[i];
            V value = mappingFunction.apply(key);
            if (value == null) { // Return the existing value, if any
                TreeNode p = e.getTreeNode(hash, key);
                if (p != null) {
                    return (V) p.entry.value;
                }
                return null;
            } else { // Put the new value into the Tree, if absent
                TreeNode p = e.putTreeNode(hash, key, value, null);
                if (p == null) { // not found, new node was added
                    modCount++;
                    size++;
                    if (size >= threshold) {
                        resize(2 * table.length);
                    }
                    return value;
                } else { // putTreeNode() found an existing node
                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                    V oldVal = pEntry.value;
                    if (oldVal == null) { // only replace if maps to null
                        pEntry.value = value;
                        pEntry.recordAccess(this);
                        return value;
                    }
                    return oldVal;
                }
            }
        }
1583
        V newValue = mappingFunction.apply(key);
1584
        if (newValue != null) { // add Entry and check for TreeBin conversion
1585
            modCount++;
1586
            addEntry(hash, key, newValue, i, checkIfNeedTree);
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
        }

        return newValue;
    }

    @Override
    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (isEmpty()) {
            return null;
        }
1597 1598 1599
        if (key == null) {
            V oldValue;
            if (nullKeyEntry != null && (oldValue = nullKeyEntry.value) != null) {
1600
                V newValue = remappingFunction.apply(key, oldValue);
1601 1602 1603
                if (newValue != null ) {
                    putForNullKey(newValue);
                    return newValue;
1604
                } else {
1605
                    removeNullKey();
1606 1607
                }
            }
1608
            return null;
1609
        }
1610
        int hash = hash(key);
1611
        int i = indexFor(hash, table.length);
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
        if (table[i] instanceof Entry) {
            @SuppressWarnings("unchecked")
            Entry<K,V> prev = (Entry<K,V>)table[i];
            Entry<K,V> e = prev;
            while (e != null) {
                Entry<K,V> next = (Entry<K,V>)e.next;
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    V oldValue = e.value;
                    if (oldValue == null)
                        break;
                    V newValue = remappingFunction.apply(key, oldValue);
1623
                    if (newValue == null) {
1624
                        modCount++;
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
                        size--;
                        if (prev == e)
                            table[i] = next;
                        else
                            prev.next = next;
                        e.recordRemoval(this);
                    } else {
                        e.value = newValue;
                        e.recordAccess(this);
                    }
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
                    return newValue;
                }
                prev = e;
                e = next;
            }
        } else if (table[i] != null) {
            TreeBin tb = (TreeBin)table[i];
            TreeNode p = tb.getTreeNode(hash, key);
            if (p != null) {
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                // assert pEntry.key.equals(key);
                V oldValue = pEntry.value;
                if (oldValue != null) {
                    V newValue = remappingFunction.apply(key, oldValue);
                    if (newValue == null) { // remove mapping
                        modCount++;
                        size--;
                        tb.deleteTreeNode(p);
                        pEntry.recordRemoval(this);
                        if (tb.root == null || tb.first == null) {
                            // assert tb.root == null && tb.first == null :
                            //     "TreeBin.first and root should both be null";
                            // TreeBin is now empty, we should blank this bin
                            table[i] = null;
                        }
                    } else {
                        pEntry.value = newValue;
                        pEntry.recordAccess(this);
                    }
                    return newValue;
                }
            }
        }
        return null;
    }

    @Override
    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null) {
            V oldValue = nullKeyEntry == null ? null : nullKeyEntry.value;
            V newValue = remappingFunction.apply(key, oldValue);
            if (newValue != oldValue) {
                if (newValue == null) {
                    removeNullKey();
                } else {
                    putForNullKey(newValue);
                }
            }
            return newValue;
        }
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?

        if (table[i] instanceof Entry) {
            int listSize = 0;
            @SuppressWarnings("unchecked")
            Entry<K,V> prev = (Entry<K,V>)table[i];
            Entry<K,V> e = prev;

            while (e != null) {
                Entry<K,V> next = (Entry<K,V>)e.next;
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    V oldValue = e.value;
                    V newValue = remappingFunction.apply(key, oldValue);
                    if (newValue != oldValue) {
                        if (newValue == null) {
                            modCount++;
                            size--;
                            if (prev == e)
                                table[i] = next;
                            else
                                prev.next = next;
                            e.recordRemoval(this);
                        } else {
                            e.value = newValue;
                            e.recordAccess(this);
                        }
                    }
                    return newValue;
                }
                prev = e;
                e = next;
                listSize++;
            }
            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
        } else if (table[i] != null) {
            TreeBin tb = (TreeBin)table[i];
            TreeNode p = tb.getTreeNode(hash, key);
            V oldValue = p == null ? null : (V)p.entry.value;
            V newValue = remappingFunction.apply(key, oldValue);
            if (newValue != oldValue) {
                if (newValue == null) {
                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                    modCount++;
                    size--;
                    tb.deleteTreeNode(p);
                    pEntry.recordRemoval(this);
                    if (tb.root == null || tb.first == null) {
                        // assert tb.root == null && tb.first == null :
                        //         "TreeBin.first and root should both be null";
                        // TreeBin is now empty, we should blank this bin
                        table[i] = null;
                    }
                } else {
                    if (p != null) { // just update the value
                        Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                        pEntry.value = newValue;
                        pEntry.recordAccess(this);
                    } else { // need to put new node
                        p = tb.putTreeNode(hash, key, newValue, null);
                        // assert p == null; // should have added a new node
                        modCount++;
                        size++;
                        if (size >= threshold) {
                            resize(2 * table.length);
                        }
                    }
1756 1757
                }
            }
1758
            return newValue;
1759 1760 1761 1762 1763
        }

        V newValue = remappingFunction.apply(key, null);
        if (newValue != null) {
            modCount++;
1764
            addEntry(hash, key, newValue, i, checkIfNeedTree);
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
        }

        return newValue;
    }

    @Override
    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
        if (key == null) {
            V oldValue = nullKeyEntry == null ? null : nullKeyEntry.value;
            V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value);
            if (newValue != null) {
                putForNullKey(newValue);
            } else if (nullKeyEntry != null) {
                removeNullKey();
            }
            return newValue;
        }
        int hash = hash(key);
1786
        int i = indexFor(hash, table.length);
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?

        if (table[i] instanceof Entry) {
            int listSize = 0;
            @SuppressWarnings("unchecked")
            Entry<K,V> prev = (Entry<K,V>)table[i];
            Entry<K,V> e = prev;

            while (e != null) {
                Entry<K,V> next = (Entry<K,V>)e.next;
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    V oldValue = e.value;
                    V newValue = (oldValue == null) ? value :
                                 remappingFunction.apply(oldValue, value);
                    if (newValue == null) {
                        modCount++;
                        size--;
                        if (prev == e)
                            table[i] = next;
                        else
                            prev.next = next;
                        e.recordRemoval(this);
                    } else {
                        e.value = newValue;
                        e.recordAccess(this);
                    }
                    return newValue;
                }
                prev = e;
                e = next;
                listSize++;
            }
            // Didn't find, so fall through and (maybe) call addEntry() to add
            // the Entry and check for TreeBin conversion.
            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
        } else if (table[i] != null) {
            TreeBin tb = (TreeBin)table[i];
            TreeNode p = tb.getTreeNode(hash, key);
            V oldValue = p == null ? null : (V)p.entry.value;
            V newValue = (oldValue == null) ? value :
                         remappingFunction.apply(oldValue, value);
            if (newValue == null) {
                if (p != null) {
                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                    modCount++;
1832
                    size--;
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
                    tb.deleteTreeNode(p);
                    pEntry.recordRemoval(this);

                    if (tb.root == null || tb.first == null) {
                        // assert tb.root == null && tb.first == null :
                        //         "TreeBin.first and root should both be null";
                        // TreeBin is now empty, we should blank this bin
                        table[i] = null;
                    }
                }
                return null;
            } else if (newValue != oldValue) {
                if (p != null) { // just update the value
                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                    pEntry.value = newValue;
                    pEntry.recordAccess(this);
                } else { // need to put new node
                    p = tb.putTreeNode(hash, key, newValue, null);
                    // assert p == null; // should have added a new node
                    modCount++;
                    size++;
                    if (size >= threshold) {
                        resize(2 * table.length);
                    }
1857 1858
                }
            }
1859
            return newValue;
1860 1861 1862
        }
        if (value != null) {
            modCount++;
1863
            addEntry(hash, key, value, i, checkIfNeedTree);
1864 1865 1866 1867 1868 1869
        }
        return value;
    }

    // end of optimized implementations of default methods in Map

D
duke 已提交
1870 1871 1872 1873
    /**
     * Removes and returns the entry associated with the specified key
     * in the HashMap.  Returns null if the HashMap contains no mapping
     * for this key.
1874 1875 1876 1877
     *
     * We don't bother converting TreeBins back to Entry lists if the bin falls
     * back below TREE_THRESHOLD, but we do clear bins when removing the last
     * TreeNode in a TreeBin.
D
duke 已提交
1878 1879
     */
    final Entry<K,V> removeEntryForKey(Object key) {
1880 1881 1882
        if (isEmpty()) {
            return null;
        }
1883 1884 1885 1886 1887 1888 1889
        if (key == null) {
            if (nullKeyEntry != null) {
                return removeNullKey();
            }
            return null;
        }
        int hash = hash(key);
D
duke 已提交
1890
        int i = indexFor(hash, table.length);
1891 1892 1893

        if (table[i] instanceof Entry) {
            @SuppressWarnings("unchecked")
1894
            Entry<K,V> prev = (Entry<K,V>)table[i];
1895
            Entry<K,V> e = prev;
D
duke 已提交
1896

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
            while (e != null) {
                @SuppressWarnings("unchecked")
                Entry<K,V> next = (Entry<K,V>) e.next;
                if (e.hash == hash && Objects.equals(e.key, key)) {
                    modCount++;
                    size--;
                    if (prev == e)
                        table[i] = next;
                    else
                        prev.next = next;
                    e.recordRemoval(this);
                    return e;
                }
                prev = e;
                e = next;
            }
        } else if (table[i] != null) {
            TreeBin tb = ((TreeBin) table[i]);
            TreeNode p = tb.getTreeNode(hash, (K)key);
            if (p != null) {
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                // assert pEntry.key.equals(key);
D
duke 已提交
1919 1920
                modCount++;
                size--;
1921 1922 1923 1924 1925 1926 1927 1928 1929
                tb.deleteTreeNode(p);
                pEntry.recordRemoval(this);
                if (tb.root == null || tb.first == null) {
                    // assert tb.root == null && tb.first == null :
                    //             "TreeBin.first and root should both be null";
                    // TreeBin is now empty, we should blank this bin
                    table[i] = null;
                }
                return pEntry;
D
duke 已提交
1930 1931
            }
        }
1932
        return null;
D
duke 已提交
1933 1934 1935
    }

    /**
1936 1937
     * Special version of remove for EntrySet using {@code Map.Entry.equals()}
     * for matching.
D
duke 已提交
1938 1939
     */
    final Entry<K,V> removeMapping(Object o) {
1940
        if (isEmpty() || !(o instanceof Map.Entry))
D
duke 已提交
1941 1942
            return null;

1943
        Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
D
duke 已提交
1944
        Object key = entry.getKey();
1945 1946 1947 1948 1949 1950 1951 1952 1953

        if (key == null) {
            if (entry.equals(nullKeyEntry)) {
                return removeNullKey();
            }
            return null;
        }

        int hash = hash(key);
D
duke 已提交
1954 1955
        int i = indexFor(hash, table.length);

1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
        if (table[i] instanceof Entry) {
            @SuppressWarnings("unchecked")
                Entry<K,V> prev = (Entry<K,V>)table[i];
            Entry<K,V> e = prev;

            while (e != null) {
                @SuppressWarnings("unchecked")
                Entry<K,V> next = (Entry<K,V>)e.next;
                if (e.hash == hash && e.equals(entry)) {
                    modCount++;
                    size--;
                    if (prev == e)
                        table[i] = next;
                    else
                        prev.next = next;
                    e.recordRemoval(this);
                    return e;
                }
                prev = e;
                e = next;
            }
        } else if (table[i] != null) {
            TreeBin tb = ((TreeBin) table[i]);
            TreeNode p = tb.getTreeNode(hash, (K)key);
            if (p != null && p.entry.equals(entry)) {
                @SuppressWarnings("unchecked")
                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
                // assert pEntry.key.equals(key);
D
duke 已提交
1984 1985
                modCount++;
                size--;
1986 1987 1988 1989 1990 1991 1992 1993 1994
                tb.deleteTreeNode(p);
                pEntry.recordRemoval(this);
                if (tb.root == null || tb.first == null) {
                    // assert tb.root == null && tb.first == null :
                    //             "TreeBin.first and root should both be null";
                    // TreeBin is now empty, we should blank this bin
                    table[i] = null;
                }
                return pEntry;
D
duke 已提交
1995 1996
            }
        }
1997 1998
        return null;
    }
D
duke 已提交
1999

2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
    /*
     * Remove the mapping for the null key, and update internal accounting
     * (size, modcount, recordRemoval, etc).
     *
     * Assumes nullKeyEntry is non-null.
     */
    private Entry<K,V> removeNullKey() {
        // assert nullKeyEntry != null;
        Entry<K,V> retVal = nullKeyEntry;
        modCount++;
        size--;
        retVal.recordRemoval(this);
        nullKeyEntry = null;
        return retVal;
D
duke 已提交
2014 2015 2016 2017 2018 2019 2020 2021
    }

    /**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {
        modCount++;
2022 2023 2024
        if (nullKeyEntry != null) {
            nullKeyEntry = null;
        }
2025
        Arrays.fill(table, null);
D
duke 已提交
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
        size = 0;
    }

    /**
     * Returns <tt>true</tt> if this map maps one or more keys to the
     * specified value.
     *
     * @param value value whose presence in this map is to be tested
     * @return <tt>true</tt> if this map maps one or more keys to the
     *         specified value
     */
    public boolean containsValue(Object value) {
2038
        if (value == null) {
D
duke 已提交
2039
            return containsNullValue();
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
        }
        Object[] tab = table;
        for (int i = 0; i < tab.length; i++) {
            if (tab[i] instanceof Entry) {
                Entry<?,?> e = (Entry<?,?>)tab[i];
                for (; e != null; e = (Entry<?,?>)e.next) {
                    if (value.equals(e.value)) {
                        return true;
                    }
                }
            } else if (tab[i] != null) {
                TreeBin e = (TreeBin)tab[i];
                TreeNode p = e.first;
                for (; p != null; p = (TreeNode) p.entry.next) {
                    if (value == p.entry.value || value.equals(p.entry.value)) {
                        return true;
                    }
                }
            }
        }
        // Didn't find value in table - could be in nullKeyEntry
        return (nullKeyEntry != null && (value == nullKeyEntry.value ||
                                         value.equals(nullKeyEntry.value)));
D
duke 已提交
2063 2064 2065 2066 2067 2068
    }

    /**
     * Special-case code for containsValue with null argument
     */
    private boolean containsNullValue() {
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
        Object[] tab = table;
        for (int i = 0; i < tab.length; i++) {
            if (tab[i] instanceof Entry) {
                Entry<K,V> e = (Entry<K,V>)tab[i];
                for (; e != null; e = (Entry<K,V>)e.next) {
                    if (e.value == null) {
                        return true;
                    }
                }
            } else if (tab[i] != null) {
                TreeBin e = (TreeBin)tab[i];
                TreeNode p = e.first;
                for (; p != null; p = (TreeNode) p.entry.next) {
                    if (p.entry.value == null) {
                        return true;
                    }
                }
            }
        }
        // Didn't find value in table - could be in nullKeyEntry
        return (nullKeyEntry != null && nullKeyEntry.value == null);
D
duke 已提交
2090 2091 2092 2093 2094 2095 2096 2097
    }

    /**
     * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
     * values themselves are not cloned.
     *
     * @return a shallow copy of this map
     */
2098
    @SuppressWarnings("unchecked")
D
duke 已提交
2099 2100 2101 2102 2103 2104 2105
    public Object clone() {
        HashMap<K,V> result = null;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // assert false;
        }
2106 2107 2108 2109 2110 2111 2112 2113
        if (result.table != EMPTY_TABLE) {
            result.inflateTable(Math.min(
                (int) Math.min(
                    size * Math.min(1 / loadFactor, 4.0f),
                    // we have limits...
                    HashMap.MAXIMUM_CAPACITY),
                table.length));
        }
D
duke 已提交
2114 2115 2116
        result.entrySet = null;
        result.modCount = 0;
        result.size = 0;
2117
        result.nullKeyEntry = null;
D
duke 已提交
2118 2119 2120 2121 2122 2123 2124 2125 2126
        result.init();
        result.putAllForCreate(this);

        return result;
    }

    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
2127
        Object next; // an Entry, or a TreeNode
D
duke 已提交
2128 2129 2130 2131 2132
        final int hash;

        /**
         * Creates new entry.
         */
2133
        Entry(int h, K k, V v, Object n) {
D
duke 已提交
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
            value = v;
            next = n;
            key = k;
            hash = h;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
2157
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
D
duke 已提交
2158 2159 2160 2161 2162 2163 2164
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
2165
                }
D
duke 已提交
2166 2167 2168 2169
            return false;
        }

        public final int hashCode() {
2170
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
D
duke 已提交
2171 2172 2173 2174 2175 2176 2177 2178
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
2179
         * overwritten for a key that's already in the HashMap.
D
duke 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }

2192 2193 2194 2195
    void addEntry(int hash, K key, V value, int bucketIndex) {
        addEntry(hash, key, value, bucketIndex, true);
    }

D
duke 已提交
2196 2197 2198
    /**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
2199 2200
     * method to resize the table if appropriate.  The new entry is then
     * created by calling createEntry().
D
duke 已提交
2201 2202
     *
     * Subclass overrides this to alter the behavior of put method.
2203 2204 2205 2206 2207
     *
     * If checkIfNeedTree is false, it is known that this bucket will not need
     * to be converted to a TreeBin, so don't bothering checking.
     *
     * Assumes key is not null.
D
duke 已提交
2208
     */
2209 2210
    void addEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
        // assert key != null;
2211
        if ((size >= threshold) && (null != table[bucketIndex])) {
D
duke 已提交
2212
            resize(2 * table.length);
2213
            hash = hash(key);
2214 2215
            bucketIndex = indexFor(hash, table.length);
        }
2216
        createEntry(hash, key, value, bucketIndex, checkIfNeedTree);
D
duke 已提交
2217 2218 2219
    }

    /**
2220
     * Called by addEntry(), and also used when creating entries
D
duke 已提交
2221
     * as part of Map construction or "pseudo-construction" (cloning,
2222 2223 2224 2225 2226 2227
     * deserialization).  This version does not check for resizing of the table.
     *
     * This method is responsible for converting a bucket to a TreeBin once
     * TREE_THRESHOLD is reached. However if checkIfNeedTree is false, it is known
     * that this bucket will not need to be converted to a TreeBin, so don't
     * bother checking.  The new entry is constructed by calling newEntry().
D
duke 已提交
2228
     *
2229 2230 2231 2232
     * Assumes key is not null.
     *
     * Note: buckets already converted to a TreeBin don't call this method, but
     * instead call TreeBin.putTreeNode() to create new entries.
D
duke 已提交
2233
     */
2234 2235
    void createEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
        // assert key != null;
2236 2237
        @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>)table[bucketIndex];
2238
        table[bucketIndex] = newEntry(hash, key, value, e);
D
duke 已提交
2239
        size++;
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261

        if (checkIfNeedTree) {
            int listSize = 0;
            for (e = (Entry<K,V>) table[bucketIndex]; e != null; e = (Entry<K,V>)e.next) {
                listSize++;
                if (listSize >= TreeBin.TREE_THRESHOLD) { // Convert to TreeBin
                    if (comparableClassFor(key) != null) {
                        TreeBin t = new TreeBin();
                        t.populate((Entry)table[bucketIndex]);
                        table[bucketIndex] = t;
                    }
                    break;
                }
            }
        }
    }

    /*
     * Factory method to create a new Entry object.
     */
    Entry<K,V> newEntry(int hash, K key, V value, Object next) {
        return new HashMap.Entry<>(hash, key, value, next);
D
duke 已提交
2262 2263
    }

2264

D
duke 已提交
2265
    private abstract class HashIterator<E> implements Iterator<E> {
2266
        Object next;            // next entry to return, an Entry or a TreeNode
D
duke 已提交
2267 2268
        int expectedModCount;   // For fast-fail
        int index;              // current slot
2269
        Object current;         // current entry, an Entry or a TreeNode
D
duke 已提交
2270 2271 2272 2273

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
2274 2275 2276 2277 2278 2279 2280 2281
                if (nullKeyEntry != null) {
                    // assert nullKeyEntry.next == null;
                    // This works with nextEntry(): nullKeyEntry isa Entry, and
                    // e.next will be null, so we'll hit the findNextBin() call.
                    next = nullKeyEntry;
                } else {
                    findNextBin();
                }
D
duke 已提交
2282 2283 2284 2285 2286 2287 2288
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

2289
        @SuppressWarnings("unchecked")
D
duke 已提交
2290
        final Entry<K,V> nextEntry() {
2291
            if (modCount != expectedModCount) {
D
duke 已提交
2292
                throw new ConcurrentModificationException();
2293 2294 2295 2296
            }
            Object e = next;
            Entry<K,V> retVal;

D
duke 已提交
2297 2298 2299
            if (e == null)
                throw new NoSuchElementException();

2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
            if (e instanceof Entry) {
                retVal = (Entry<K,V>)e;
                next = ((Entry<K,V>)e).next;
            } else { // TreeBin
                retVal = (Entry<K,V>)((TreeNode)e).entry;
                next = retVal.next;
            }

            if (next == null) { // Move to next bin
                findNextBin();
D
duke 已提交
2310 2311
            }
            current = e;
2312
            return retVal;
D
duke 已提交
2313 2314 2315 2316 2317 2318 2319
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
2320 2321 2322 2323 2324 2325 2326 2327
            K k;

            if (current instanceof Entry) {
                k = ((Entry<K,V>)current).key;
            } else {
                k = ((Entry<K,V>)((TreeNode)current).entry).key;

            }
D
duke 已提交
2328 2329 2330 2331
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346

        /*
         * Set 'next' to the first entry of the next non-empty bin in the table
         */
        private void findNextBin() {
            // assert next == null;
            Object[] t = table;

            while (index < t.length && (next = t[index++]) == null)
                ;
            if (next instanceof HashMap.TreeBin) { // Point to the first TreeNode
                next = ((TreeBin) next).first;
                // assert next != null; // There should be no empty TreeBins
            }
        }
D
duke 已提交
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
    }

    private final class ValueIterator extends HashIterator<V> {
        public V next() {
            return nextEntry().value;
        }
    }

    private final class KeyIterator extends HashIterator<K> {
        public K next() {
            return nextEntry().getKey();
        }
    }

    private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() {
            return nextEntry();
        }
    }

    // Subclass overrides these to alter behavior of views' iterator() method
    Iterator<K> newKeyIterator()   {
        return new KeyIterator();
    }
    Iterator<V> newValueIterator()   {
        return new ValueIterator();
    }
    Iterator<Map.Entry<K,V>> newEntryIterator()   {
        return new EntryIterator();
    }


    // Views

    private transient Set<Map.Entry<K,V>> entrySet = null;

    /**
     * Returns a {@link Set} view of the keys contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
     * operations.
     */
    public Set<K> keySet() {
        Set<K> ks = keySet;
        return (ks != null ? ks : (keySet = new KeySet()));
    }

    private final class KeySet extends AbstractSet<K> {
        public Iterator<K> iterator() {
            return newKeyIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsKey(o);
        }
        public boolean remove(Object o) {
            return HashMap.this.removeEntryForKey(o) != null;
        }
        public void clear() {
            HashMap.this.clear();
        }
2417 2418 2419 2420 2421 2422 2423 2424

        public Spliterator<K> spliterator() {
            if (HashMap.this.getClass() == HashMap.class)
                return new KeySpliterator<K,V>(HashMap.this, 0, -1, 0, 0);
            else
                return Spliterators.spliterator
                        (this, Spliterator.SIZED | Spliterator.DISTINCT);
        }
D
duke 已提交
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
    }

    /**
     * Returns a {@link Collection} view of the values contained in this map.
     * The collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.  If the map is
     * modified while an iteration over the collection is in progress
     * (except through the iterator's own <tt>remove</tt> operation),
     * the results of the iteration are undefined.  The collection
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
     * support the <tt>add</tt> or <tt>addAll</tt> operations.
     */
    public Collection<V> values() {
        Collection<V> vs = values;
        return (vs != null ? vs : (values = new Values()));
    }

    private final class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return newValueIterator();
        }
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsValue(o);
        }
        public void clear() {
            HashMap.this.clear();
        }
2458 2459 2460 2461 2462 2463 2464 2465

        public Spliterator<V> spliterator() {
            if (HashMap.this.getClass() == HashMap.class)
                return new ValueSpliterator<K,V>(HashMap.this, 0, -1, 0, 0);
            else
                return Spliterators.spliterator
                        (this, Spliterator.SIZED);
        }
D
duke 已提交
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
    }

    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation, or through the
     * <tt>setValue</tt> operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
     * <tt>clear</tt> operations.  It does not support the
     * <tt>add</tt> or <tt>addAll</tt> operations.
     *
     * @return a set view of the mappings contained in this map
     */
    public Set<Map.Entry<K,V>> entrySet() {
        return entrySet0();
    }

    private Set<Map.Entry<K,V>> entrySet0() {
        Set<Map.Entry<K,V>> es = entrySet;
        return es != null ? es : (entrySet = new EntrySet());
    }

    private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return newEntryIterator();
        }
        public boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
2500
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
D
duke 已提交
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
            Entry<K,V> candidate = getEntry(e.getKey());
            return candidate != null && candidate.equals(e);
        }
        public boolean remove(Object o) {
            return removeMapping(o) != null;
        }
        public int size() {
            return size;
        }
        public void clear() {
            HashMap.this.clear();
        }
2513 2514 2515 2516 2517 2518 2519 2520

        public Spliterator<Map.Entry<K,V>> spliterator() {
            if (HashMap.this.getClass() == HashMap.class)
                return new EntrySpliterator<K,V>(HashMap.this, 0, -1, 0, 0);
            else
                return Spliterators.spliterator
                        (this, Spliterator.SIZED | Spliterator.DISTINCT);
        }
D
duke 已提交
2521 2522 2523 2524 2525 2526 2527
    }

    /**
     * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
     * serialize it).
     *
     * @serialData The <i>capacity</i> of the HashMap (the length of the
2528
     *             bucket array) is emitted (int), followed by the
D
duke 已提交
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
     *             <i>size</i> (an int, the number of key-value
     *             mappings), followed by the key (Object) and value (Object)
     *             for each key-value mapping.  The key-value mappings are
     *             emitted in no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException
    {
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();

        // Write out number of buckets
2541 2542 2543
        if (table==EMPTY_TABLE) {
            s.writeInt(roundUpToPowerOf2(threshold));
        } else {
2544
            s.writeInt(table.length);
2545
        }
D
duke 已提交
2546 2547 2548 2549 2550

        // Write out size (number of Mappings)
        s.writeInt(size);

        // Write out keys and values (alternating)
2551 2552
        if (size > 0) {
            for(Map.Entry<K,V> e : entrySet0()) {
D
duke 已提交
2553 2554 2555 2556 2557 2558 2559 2560 2561
                s.writeObject(e.getKey());
                s.writeObject(e.getValue());
            }
        }
    }

    private static final long serialVersionUID = 362498820763181265L;

    /**
2562
     * Reconstitute the {@code HashMap} instance from a stream (i.e.,
D
duke 已提交
2563 2564 2565 2566 2567
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
2568
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
D
duke 已提交
2569
        s.defaultReadObject();
2570
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
2571 2572
            throw new InvalidObjectException("Illegal load factor: " +
                                               loadFactor);
2573
        }
2574

2575
        // set other fields that need values
2576
        if (Holder.USE_HASHSEED) {
2577
            int seed = ThreadLocalRandom.current().nextInt();
2578
            Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
2579
                                         (seed != 0) ? seed : 1);
2580
        }
2581
        table = EMPTY_TABLE;
D
duke 已提交
2582

2583 2584
        // Read in number of buckets
        s.readInt(); // ignored.
2585 2586 2587 2588 2589 2590 2591

        // Read number of mappings
        int mappings = s.readInt();
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                               mappings);

2592 2593
        // capacity chosen by number of mappings and desired load (if >= 0.25)
        int capacity = (int) Math.min(
2594 2595 2596
                mappings * Math.min(1 / loadFactor, 4.0f),
                // we have limits...
                HashMap.MAXIMUM_CAPACITY);
2597 2598 2599 2600 2601 2602

        // allocate the bucket array;
        if (mappings > 0) {
            inflateTable(capacity);
        } else {
            threshold = capacity;
2603
        }
D
duke 已提交
2604 2605 2606 2607

        init();  // Give subclass a chance to do its thing.

        // Read the keys and values, and put the mappings in the HashMap
2608
        for (int i=0; i<mappings; i++) {
2609
            @SuppressWarnings("unchecked")
2610
            K key = (K) s.readObject();
2611
            @SuppressWarnings("unchecked")
2612
            V value = (V) s.readObject();
D
duke 已提交
2613 2614 2615 2616 2617 2618 2619
            putForCreate(key, value);
        }
    }

    // These methods are used when serializing HashSets
    int   capacity()     { return table.length; }
    float loadFactor()   { return loadFactor;   }
2620 2621 2622 2623 2624 2625

    /**
     * Standin until HM overhaul; based loosely on Weak and Identity HM.
     */
    static class HashMapSpliterator<K,V> {
        final HashMap<K,V> map;
2626
        Object current;             // current node, can be Entry or TreeNode
2627 2628 2629 2630
        int index;                  // current index, modified on advance/split
        int fence;                  // one past last index
        int est;                    // size estimate
        int expectedModCount;       // for comodification checks
2631 2632 2633 2634 2635 2636
        boolean acceptedNull;       // Have we accepted the null key?
                                    // Without this, we can't distinguish
                                    // between being at the very beginning (and
                                    // needing to accept null), or being at the
                                    // end of the list in bin 0.  In both cases,
                                    // current == null && index == 0.
2637 2638 2639 2640 2641 2642 2643 2644 2645

        HashMapSpliterator(HashMap<K,V> m, int origin,
                               int fence, int est,
                               int expectedModCount) {
            this.map = m;
            this.index = origin;
            this.fence = fence;
            this.est = est;
            this.expectedModCount = expectedModCount;
2646
            this.acceptedNull = false;
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
        }

        final int getFence() { // initialize fence and size on first use
            int hi;
            if ((hi = fence) < 0) {
                HashMap<K,V> m = map;
                est = m.size;
                expectedModCount = m.modCount;
                hi = fence = m.table.length;
            }
            return hi;
        }

        public final long estimateSize() {
            getFence(); // force init
            return (long) est;
        }
    }

    static final class KeySpliterator<K,V>
        extends HashMapSpliterator<K,V>
        implements Spliterator<K> {
        KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,
                       int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public KeySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
2676 2677 2678 2679 2680 2681 2682 2683 2684
            if (lo >= mid || current != null) {
                return null;
            } else {
                KeySpliterator<K,V> retVal = new KeySpliterator<K,V>(map, lo,
                                     index = mid, est >>>= 1, expectedModCount);
                // Only 'this' Spliterator chould check for null.
                retVal.acceptedNull = true;
                return retVal;
            }
2685 2686 2687 2688 2689 2690 2691 2692
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
2693
            Object[] tab = m.table;
2694 2695 2696 2697 2698 2699
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
2700 2701 2702 2703 2704 2705 2706

            if (!acceptedNull) {
                acceptedNull = true;
                if (m.nullKeyEntry != null) {
                    action.accept(m.nullKeyEntry.key);
                }
            }
2707 2708
            if (tab.length >= hi && (i = index) >= 0 &&
                (i < (index = hi) || current != null)) {
2709
                Object p = current;
2710
                current = null;
2711
                do {
2712
                    if (p == null) {
2713
                        p = tab[i++];
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
                        if (p instanceof HashMap.TreeBin) {
                            p = ((HashMap.TreeBin)p).first;
                        }
                    } else {
                        HashMap.Entry<K,V> entry;
                        if (p instanceof HashMap.Entry) {
                            entry = (HashMap.Entry<K,V>)p;
                        } else {
                            entry = (HashMap.Entry<K,V>)((TreeNode)p).entry;
                        }
                        action.accept(entry.key);
                        p = entry.next;
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super K> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
            Object[] tab = map.table;
            hi = getFence();

            if (!acceptedNull) {
                acceptedNull = true;
                if (map.nullKeyEntry != null) {
                    action.accept(map.nullKeyEntry.key);
                    if (map.modCount != expectedModCount)
                        throw new ConcurrentModificationException();
                    return true;
                }
            }
            if (tab.length >= hi && index >= 0) {
2751
                while (current != null || index < hi) {
2752
                    if (current == null) {
2753
                        current = tab[index++];
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
                        if (current instanceof HashMap.TreeBin) {
                            current = ((HashMap.TreeBin)current).first;
                        }
                    } else {
                        HashMap.Entry<K,V> entry;
                        if (current instanceof HashMap.Entry) {
                            entry = (HashMap.Entry<K,V>)current;
                        } else {
                            entry = (HashMap.Entry<K,V>)((TreeNode)current).entry;
                        }
                        K k = entry.key;
                        current = entry.next;
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
                        action.accept(k);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }

    static final class ValueSpliterator<K,V>
        extends HashMapSpliterator<K,V>
        implements Spliterator<V> {
        ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public ValueSpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
2792 2793 2794 2795 2796 2797 2798 2799 2800
            if (lo >= mid || current != null) {
                return null;
            } else {
                ValueSpliterator<K,V> retVal = new ValueSpliterator<K,V>(map,
                                 lo, index = mid, est >>>= 1, expectedModCount);
                // Only 'this' Spliterator chould check for null.
                retVal.acceptedNull = true;
                return retVal;
            }
2801 2802 2803 2804 2805 2806 2807 2808
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
2809
            Object[] tab = m.table;
2810 2811 2812 2813 2814 2815
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
2816 2817 2818 2819 2820 2821 2822

            if (!acceptedNull) {
                acceptedNull = true;
                if (m.nullKeyEntry != null) {
                    action.accept(m.nullKeyEntry.value);
                }
            }
2823 2824
            if (tab.length >= hi && (i = index) >= 0 &&
                (i < (index = hi) || current != null)) {
2825
                Object p = current;
2826
                current = null;
2827
                do {
2828
                    if (p == null) {
2829
                        p = tab[i++];
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
                        if (p instanceof HashMap.TreeBin) {
                            p = ((HashMap.TreeBin)p).first;
                        }
                    } else {
                        HashMap.Entry<K,V> entry;
                        if (p instanceof HashMap.Entry) {
                            entry = (HashMap.Entry<K,V>)p;
                        } else {
                            entry = (HashMap.Entry<K,V>)((TreeNode)p).entry;
                        }
                        action.accept(entry.value);
                        p = entry.next;
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super V> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
            Object[] tab = map.table;
            hi = getFence();

            if (!acceptedNull) {
                acceptedNull = true;
                if (map.nullKeyEntry != null) {
                    action.accept(map.nullKeyEntry.value);
                    if (map.modCount != expectedModCount)
                        throw new ConcurrentModificationException();
                    return true;
                }
            }
            if (tab.length >= hi && index >= 0) {
2867
                while (current != null || index < hi) {
2868
                    if (current == null) {
2869
                        current = tab[index++];
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881
                        if (current instanceof HashMap.TreeBin) {
                            current = ((HashMap.TreeBin)current).first;
                        }
                    } else {
                        HashMap.Entry<K,V> entry;
                        if (current instanceof HashMap.Entry) {
                            entry = (Entry<K,V>)current;
                        } else {
                            entry = (Entry<K,V>)((TreeNode)current).entry;
                        }
                        V v = entry.value;
                        current = entry.next;
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
                        action.accept(v);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
        }
    }

    static final class EntrySpliterator<K,V>
        extends HashMapSpliterator<K,V>
        implements Spliterator<Map.Entry<K,V>> {
        EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public EntrySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
2907 2908 2909 2910 2911 2912 2913 2914 2915
            if (lo >= mid || current != null) {
                return null;
            } else {
                EntrySpliterator<K,V> retVal = new EntrySpliterator<K,V>(map,
                                 lo, index = mid, est >>>= 1, expectedModCount);
                // Only 'this' Spliterator chould check for null.
                retVal.acceptedNull = true;
                return retVal;
            }
2916 2917 2918 2919 2920 2921 2922 2923
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
2924
            Object[] tab = m.table;
2925 2926 2927 2928 2929 2930
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
2931 2932 2933 2934 2935 2936 2937

            if (!acceptedNull) {
                acceptedNull = true;
                if (m.nullKeyEntry != null) {
                    action.accept(m.nullKeyEntry);
                }
            }
2938 2939
            if (tab.length >= hi && (i = index) >= 0 &&
                (i < (index = hi) || current != null)) {
2940
                Object p = current;
2941
                current = null;
2942
                do {
2943
                    if (p == null) {
2944
                        p = tab[i++];
2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
                        if (p instanceof HashMap.TreeBin) {
                            p = ((HashMap.TreeBin)p).first;
                        }
                    } else {
                        HashMap.Entry<K,V> entry;
                        if (p instanceof HashMap.Entry) {
                            entry = (HashMap.Entry<K,V>)p;
                        } else {
                            entry = (HashMap.Entry<K,V>)((TreeNode)p).entry;
                        }
                        action.accept(entry);
                        p = entry.next;

2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
            Object[] tab = map.table;
            hi = getFence();

            if (!acceptedNull) {
                acceptedNull = true;
                if (map.nullKeyEntry != null) {
                    action.accept(map.nullKeyEntry);
                    if (map.modCount != expectedModCount)
                        throw new ConcurrentModificationException();
                    return true;
                }
            }
            if (tab.length >= hi && index >= 0) {
2983
                while (current != null || index < hi) {
2984
                    if (current == null) {
2985
                        current = tab[index++];
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
                        if (current instanceof HashMap.TreeBin) {
                            current = ((HashMap.TreeBin)current).first;
                        }
                    } else {
                        HashMap.Entry<K,V> e;
                        if (current instanceof HashMap.Entry) {
                            e = (Entry<K,V>)current;
                        } else {
                            e = (Entry<K,V>)((TreeNode)current).entry;
                        }
                        current = e.next;
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
                        action.accept(e);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }
D
duke 已提交
3012
}