HashMap.java 113.7 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
import java.util.function.BiConsumer;
33 34 35
import java.util.function.Consumer;
import java.util.function.BiFunction;
import java.util.function.Function;
D
duke 已提交
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 132

/**
 * 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>
133
        extends AbstractMap<K,V>
D
duke 已提交
134 135 136 137 138 139
    implements Map<K,V>, Cloneable, Serializable
{

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

    /**
     * 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;

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

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

    /**
     * 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
     */
173 174
    // If table == EMPTY_TABLE then this is the initial capacity at which the
    // table will be created when inflated.
D
duke 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    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).
     */
191
    transient int modCount;
D
duke 已提交
192

193 194 195
    /**
     * Holds values which can't be initialized until after VM is booted.
     */
196 197 198 199 200 201 202 203 204
    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;

205 206
        static final boolean USE_HASHSEED;

207
        static {
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
            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;
226 227 228 229
            }
        }
    }

230
    /*
231 232
     * A randomizing value associated with this instance that is applied to
     * hash code of keys to make hash collisions harder to find.
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 320
     *
     * 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).
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 814
    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;
            }
        }
    }
815

D
duke 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    /**
     * 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;
835
        threshold = initialCapacity;
836
        hashSeed = initHashSeed();
D
duke 已提交
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
        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() {
856
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
D
duke 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869
    }

    /**
     * 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,
870
                DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
871 872
        inflateTable(threshold);

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

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

    /**
     * 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);
892
        table = new Object[capacity];
893 894
    }

D
duke 已提交
895 896 897 898 899 900 901 902 903 904 905 906
    // 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() {
    }

907 908 909 910 911 912
    /**
     * 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) {
913 914
            int seed = ThreadLocalRandom.current().nextInt();
            return (seed != 0) ? seed : 1;
915 916 917 918
        }
        return 0;
    }

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

D
duke 已提交
929 930 931 932 933 934 935 936 937 938 939
        // 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) {
940
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
D
duke 已提交
941 942 943 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
        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)
     */
979
    @SuppressWarnings("unchecked")
D
duke 已提交
980
    public V get(Object key) {
981
        Entry<K,V> entry = getEntry(key);
D
duke 已提交
982

983
        return null == entry ? null : entry.getValue();
D
duke 已提交
984 985
    }

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

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

D
duke 已提交
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    /**
     * 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.
     */
1010
    @SuppressWarnings("unchecked")
D
duke 已提交
1011
    final Entry<K,V> getEntry(Object key) {
1012
        if (size == 0) {
1013 1014
            return null;
        }
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        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 已提交
1039 1040 1041 1042
        }
        return null;
    }

1043

D
duke 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    /**
     * 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>.)
     */
1056
    @SuppressWarnings("unchecked")
D
duke 已提交
1057
    public V put(K key, V value) {
1058 1059 1060
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1061
       if (key == null)
D
duke 已提交
1062
            return putForNullKey(value);
1063
        int hash = hash(key);
D
duke 已提交
1064
        int i = indexFor(hash, table.length);
1065 1066 1067 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
        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 已提交
1103 1104 1105
            }
        }
        modCount++;
1106
        addEntry(hash, key, value, i, checkIfNeedTree);
D
duke 已提交
1107 1108 1109 1110 1111 1112 1113
        return null;
    }

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

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    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 已提交
1139 1140 1141
    /**
     * This method is used instead of put by constructors and
     * pseudoconstructors (clone, readObject).  It does not resize the table,
1142 1143
     * check for comodification, etc, though it will convert bins to TreeBins
     * as needed.  It calls createEntry rather than addEntry.
D
duke 已提交
1144
     */
1145
    @SuppressWarnings("unchecked")
D
duke 已提交
1146
    private void putForCreate(K key, V value) {
1147 1148 1149 1150 1151
        if (null == key) {
            putForCreateNullKey(value);
            return;
        }
        int hash = hash(key);
D
duke 已提交
1152
        int i = indexFor(hash, table.length);
1153
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
D
duke 已提交
1154 1155 1156 1157 1158 1159

        /**
         * 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.
         */
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        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 已提交
1170
            }
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
            // 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 已提交
1184 1185
        }

1186
        createEntry(hash, key, value, i, checkIfNeedTree);
D
duke 已提交
1187 1188 1189
    }

    private void putAllForCreate(Map<? extends K, ? extends V> m) {
D
dl 已提交
1190
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
D
duke 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
            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) {
1209
        Object[] oldTable = table;
D
duke 已提交
1210 1211 1212 1213 1214 1215
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

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

    /**
     * Transfers all entries from current table to newTable.
1224 1225
     *
     * Assumes newTable is larger than table
D
duke 已提交
1226
     */
1227
    @SuppressWarnings("unchecked")
1228 1229 1230 1231
    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 已提交
1232
        int newCapacity = newTable.length;
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
        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 已提交
1249 1250
            }
        }
1251
        Arrays.fill(table, null);
D
duke 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    }

    /**
     * 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;

1267 1268 1269 1270
        if (table == EMPTY_TABLE) {
            inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
        }

D
duke 已提交
1271 1272 1273 1274 1275 1276 1277 1278 1279
        /*
         * 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.
         */
1280 1281
        if (numKeysToBeAdded > threshold && table.length < MAXIMUM_CAPACITY) {
            resize(table.length * 2);
D
duke 已提交
1282 1283
        }

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

    /**
     * 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);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
       return (e == null ? null : e.value);
   }

   // optimized implementations of default methods in Map

    @Override
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        if (nullKeyEntry != null) {
            forEachNullKey(expectedModCount, action);
        }
        Object[] tab = this.table;
        for (int index = 0; index < tab.length; index++) {
            Object item = tab[index];
            if (item == null) {
                continue;
            }
            if (item instanceof HashMap.TreeBin) {
                eachTreeNode(expectedModCount, ((TreeBin)item).first, action);
                continue;
            }
            @SuppressWarnings("unchecked")
            Entry<K, V> entry = (Entry<K, V>)item;
            while (entry != null) {
                action.accept(entry.key, entry.value);
                entry = (Entry<K, V>)entry.next;

                if (expectedModCount != modCount) {
                    throw new ConcurrentModificationException();
                }
            }
        }
    }

    private void eachTreeNode(int expectedModCount, TreeNode<K, V> node, BiConsumer<? super K, ? super V> action) {
        while (node != null) {
            @SuppressWarnings("unchecked")
            Entry<K, V> entry = (Entry<K, V>)node.entry;
            action.accept(entry.key, entry.value);
            node = (TreeNode<K, V>)entry.next;

            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
        }
    }

    private void forEachNullKey(int expectedModCount, BiConsumer<? super K, ? super V> action) {
        action.accept(null, nullKeyEntry.value);

        if (expectedModCount != modCount) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Objects.requireNonNull(function);
        final int expectedModCount = modCount;
        if (nullKeyEntry != null) {
            replaceforNullKey(expectedModCount, function);
        }
        Object[] tab = this.table;
        for (int index = 0; index < tab.length; index++) {
            Object item = tab[index];
            if (item == null) {
                continue;
            }
            if (item instanceof HashMap.TreeBin) {
                replaceEachTreeNode(expectedModCount, ((TreeBin)item).first, function);
                continue;
            }
            @SuppressWarnings("unchecked")
            Entry<K, V> entry = (Entry<K, V>)item;
            while (entry != null) {
                entry.value = function.apply(entry.key, entry.value);
                entry = (Entry<K, V>)entry.next;

                if (expectedModCount != modCount) {
                    throw new ConcurrentModificationException();
                }
            }
        }
D
duke 已提交
1383 1384
    }

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    private void replaceEachTreeNode(int expectedModCount, TreeNode<K, V> node, BiFunction<? super K, ? super V, ? extends V> function) {
        while (node != null) {
            @SuppressWarnings("unchecked")
            Entry<K, V> entry = (Entry<K, V>)node.entry;
            entry.value = function.apply(entry.key, entry.value);
            node = (TreeNode<K, V>)entry.next;

            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
        }
    }

    private void replaceforNullKey(int expectedModCount, BiFunction<? super K, ? super V, ? extends V> function) {
        nullKeyEntry.value = function.apply(null, nullKeyEntry.value);

        if (expectedModCount != modCount) {
            throw new ConcurrentModificationException();
        }
    }
1405 1406 1407 1408 1409 1410

    @Override
    public V putIfAbsent(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1411 1412 1413 1414 1415 1416 1417 1418 1419
        if (key == null) {
            if (nullKeyEntry == null || nullKeyEntry.value == null) {
                putForNullKey(value);
                return null;
            } else {
                return nullKeyEntry.value;
            }
        }
        int hash = hash(key);
1420
        int i = indexFor(hash, table.length);
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
        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;
1434
                }
1435 1436 1437 1438 1439 1440 1441 1442 1443
                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
1444
                modCount++;
1445 1446 1447 1448
                size++;
                if (size >= threshold) {
                    resize(2 * table.length);
                }
1449
                return null;
1450 1451 1452 1453 1454 1455 1456 1457
            } 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;
1458 1459 1460
            }
        }
        modCount++;
1461
        addEntry(hash, key, value, i, checkIfNeedTree);
1462 1463 1464 1465 1466
        return null;
    }

    @Override
    public boolean remove(Object key, Object value) {
1467
        if (size == 0) {
1468 1469
            return false;
        }
1470 1471 1472 1473 1474 1475 1476 1477 1478
        if (key == null) {
            if (nullKeyEntry != null &&
                 Objects.equals(nullKeyEntry.value, value)) {
                removeNullKey();
                return true;
            }
            return false;
        }
        int hash = hash(key);
1479 1480
        int i = indexFor(hash, table.length);

1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
        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;
1522 1523 1524 1525 1526 1527 1528 1529
                }
            }
        }
        return false;
    }

    @Override
    public boolean replace(K key, V oldValue, V newValue) {
1530
        if (size == 0) {
1531 1532
            return false;
        }
1533 1534 1535 1536
        if (key == null) {
            if (nullKeyEntry != null &&
                 Objects.equals(nullKeyEntry.value, oldValue)) {
                putForNullKey(newValue);
1537 1538
                return true;
            }
1539
            return false;
1540
        }
1541 1542
        int hash = hash(key);
        int i = indexFor(hash, table.length);
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
        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;
                }
            }
        }
1568 1569 1570
        return false;
    }

1571
   @Override
1572
    public V replace(K key, V value) {
1573
        if (size == 0) {
1574 1575
            return null;
        }
1576 1577 1578 1579 1580 1581 1582
        if (key == null) {
            if (nullKeyEntry != null) {
                return putForNullKey(value);
            }
            return null;
        }
        int hash = hash(key);
1583
        int i = indexFor(hash, table.length);
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
        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);
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
                return oldValue;
            }
        }
        return null;
    }

    @Override
    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1617 1618 1619 1620 1621 1622 1623
        if (key == null) {
            if (nullKeyEntry == null || nullKeyEntry.value == null) {
                V newValue = mappingFunction.apply(key);
                if (newValue != null) {
                    putForNullKey(newValue);
                }
                return newValue;
1624
            }
1625
            return nullKeyEntry.value;
1626
        }
1627 1628 1629
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
1630

1631 1632 1633 1634 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
        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;
                }
            }
        }
1682
        V newValue = mappingFunction.apply(key);
1683
        if (newValue != null) { // add Entry and check for TreeBin conversion
1684
            modCount++;
1685
            addEntry(hash, key, newValue, i, checkIfNeedTree);
1686 1687 1688 1689 1690 1691 1692
        }

        return newValue;
    }

    @Override
    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1693
        if (size == 0) {
1694 1695
            return null;
        }
1696 1697 1698
        if (key == null) {
            V oldValue;
            if (nullKeyEntry != null && (oldValue = nullKeyEntry.value) != null) {
1699
                V newValue = remappingFunction.apply(key, oldValue);
1700 1701 1702
                if (newValue != null ) {
                    putForNullKey(newValue);
                    return newValue;
1703
                } else {
1704
                    removeNullKey();
1705 1706
                }
            }
1707
            return null;
1708
        }
1709
        int hash = hash(key);
1710
        int i = indexFor(hash, table.length);
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
        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);
1722
                    if (newValue == null) {
1723
                        modCount++;
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
                        size--;
                        if (prev == e)
                            table[i] = next;
                        else
                            prev.next = next;
                        e.recordRemoval(this);
                    } else {
                        e.value = newValue;
                        e.recordAccess(this);
                    }
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
                    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);
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
                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;
1758
                    }
1759 1760 1761
                } else {
                    pEntry.value = newValue;
                    pEntry.recordAccess(this);
1762
                }
1763
                return newValue;
1764 1765
            }
        }
1766
        }
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
        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);
1778
            if (newValue != oldValue || (oldValue == null && nullKeyEntry != null)) {
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
                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);
1802
                    if (newValue != oldValue || oldValue == null) {
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
                        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);
1828
            if (newValue != oldValue || (oldValue == null && p != null)) {
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
                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);
                        }
                    }
1855 1856
                }
            }
1857
            return newValue;
1858 1859 1860 1861 1862
        }

        V newValue = remappingFunction.apply(key, null);
        if (newValue != null) {
            modCount++;
1863
            addEntry(hash, key, newValue, i, checkIfNeedTree);
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
        }

        return newValue;
    }

    @Override
    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
        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);
1885
        int i = indexFor(hash, table.length);
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
        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++;
1931
                    size--;
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
                    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);
                    }
1956 1957
                }
            }
1958
            return newValue;
1959 1960 1961
        }
        if (value != null) {
            modCount++;
1962
            addEntry(hash, key, value, i, checkIfNeedTree);
1963 1964 1965 1966 1967 1968
        }
        return value;
    }

    // end of optimized implementations of default methods in Map

D
duke 已提交
1969 1970 1971 1972
    /**
     * Removes and returns the entry associated with the specified key
     * in the HashMap.  Returns null if the HashMap contains no mapping
     * for this key.
1973 1974 1975 1976
     *
     * 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 已提交
1977 1978
     */
    final Entry<K,V> removeEntryForKey(Object key) {
1979
        if (size == 0) {
1980 1981
            return null;
        }
1982 1983 1984 1985 1986 1987 1988
        if (key == null) {
            if (nullKeyEntry != null) {
                return removeNullKey();
            }
            return null;
        }
        int hash = hash(key);
D
duke 已提交
1989
        int i = indexFor(hash, table.length);
1990 1991 1992

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

1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
            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 已提交
2018 2019
                modCount++;
                size--;
2020 2021 2022 2023 2024 2025 2026 2027 2028
                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 已提交
2029 2030
            }
        }
2031
        return null;
D
duke 已提交
2032 2033 2034
    }

    /**
2035 2036
     * Special version of remove for EntrySet using {@code Map.Entry.equals()}
     * for matching.
D
duke 已提交
2037 2038
     */
    final Entry<K,V> removeMapping(Object o) {
2039
        if (size == 0 || !(o instanceof Map.Entry))
D
duke 已提交
2040 2041
            return null;

2042
        Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
D
duke 已提交
2043
        Object key = entry.getKey();
2044 2045 2046 2047 2048 2049 2050 2051 2052

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

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

2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
        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 已提交
2083 2084
                modCount++;
                size--;
2085 2086 2087 2088 2089 2090 2091 2092 2093
                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 已提交
2094 2095
            }
        }
2096 2097
        return null;
    }
D
duke 已提交
2098

2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
    /*
     * 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 已提交
2113 2114 2115 2116 2117 2118 2119 2120
    }

    /**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {
        modCount++;
2121 2122 2123
        if (nullKeyEntry != null) {
            nullKeyEntry = null;
        }
2124
        Arrays.fill(table, null);
D
duke 已提交
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
        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) {
2137
        if (value == null) {
D
duke 已提交
2138
            return containsNullValue();
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
        }
        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 已提交
2162 2163 2164 2165 2166 2167
    }

    /**
     * Special-case code for containsValue with null argument
     */
    private boolean containsNullValue() {
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
        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 已提交
2189 2190 2191 2192 2193 2194 2195 2196
    }

    /**
     * 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
     */
2197
    @SuppressWarnings("unchecked")
D
duke 已提交
2198 2199 2200 2201 2202 2203 2204
    public Object clone() {
        HashMap<K,V> result = null;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // assert false;
        }
2205 2206 2207 2208 2209 2210 2211 2212
        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 已提交
2213 2214 2215
        result.entrySet = null;
        result.modCount = 0;
        result.size = 0;
2216
        result.nullKeyEntry = null;
D
duke 已提交
2217 2218 2219 2220 2221 2222 2223 2224 2225
        result.init();
        result.putAllForCreate(this);

        return result;
    }

    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
2226
        Object next; // an Entry, or a TreeNode
D
duke 已提交
2227 2228 2229 2230 2231
        final int hash;

        /**
         * Creates new entry.
         */
2232
        Entry(int h, K k, V v, Object n) {
D
duke 已提交
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
            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;
2256
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
D
duke 已提交
2257 2258 2259 2260 2261 2262 2263
            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;
2264
                }
D
duke 已提交
2265 2266 2267 2268
            return false;
        }

        public final int hashCode() {
2269
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
D
duke 已提交
2270 2271 2272 2273 2274 2275 2276 2277
        }

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

        /**
         * This method is invoked whenever the value in an entry is
2278
         * overwritten for a key that's already in the HashMap.
D
duke 已提交
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
         */
        void recordAccess(HashMap<K,V> m) {
        }

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

2291 2292 2293 2294
    void addEntry(int hash, K key, V value, int bucketIndex) {
        addEntry(hash, key, value, bucketIndex, true);
    }

D
duke 已提交
2295 2296 2297
    /**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
2298 2299
     * method to resize the table if appropriate.  The new entry is then
     * created by calling createEntry().
D
duke 已提交
2300 2301
     *
     * Subclass overrides this to alter the behavior of put method.
2302 2303 2304 2305 2306
     *
     * 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 已提交
2307
     */
2308 2309
    void addEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
        // assert key != null;
2310
        if ((size >= threshold) && (null != table[bucketIndex])) {
D
duke 已提交
2311
            resize(2 * table.length);
2312
            hash = hash(key);
2313 2314
            bucketIndex = indexFor(hash, table.length);
        }
2315
        createEntry(hash, key, value, bucketIndex, checkIfNeedTree);
D
duke 已提交
2316 2317 2318
    }

    /**
2319
     * Called by addEntry(), and also used when creating entries
D
duke 已提交
2320
     * as part of Map construction or "pseudo-construction" (cloning,
2321 2322 2323 2324 2325 2326
     * 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 已提交
2327
     *
2328 2329 2330 2331
     * 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 已提交
2332
     */
2333 2334
    void createEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
        // assert key != null;
2335 2336
        @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>)table[bucketIndex];
2337
        table[bucketIndex] = newEntry(hash, key, value, e);
D
duke 已提交
2338
        size++;
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360

        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 已提交
2361 2362
    }

2363

D
duke 已提交
2364
    private abstract class HashIterator<E> implements Iterator<E> {
2365
        Object next;            // next entry to return, an Entry or a TreeNode
D
duke 已提交
2366 2367
        int expectedModCount;   // For fast-fail
        int index;              // current slot
2368
        Object current;         // current entry, an Entry or a TreeNode
D
duke 已提交
2369 2370 2371 2372

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
2373 2374 2375 2376 2377 2378 2379 2380
                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 已提交
2381 2382 2383 2384 2385 2386 2387
            }
        }

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

2388
        @SuppressWarnings("unchecked")
D
duke 已提交
2389
        final Entry<K,V> nextEntry() {
2390
            if (modCount != expectedModCount) {
D
duke 已提交
2391
                throw new ConcurrentModificationException();
2392 2393 2394 2395
            }
            Object e = next;
            Entry<K,V> retVal;

D
duke 已提交
2396 2397 2398
            if (e == null)
                throw new NoSuchElementException();

2399
            if (e instanceof TreeNode) { // TreeBin
2400 2401
                retVal = (Entry<K,V>)((TreeNode)e).entry;
                next = retVal.next;
2402 2403 2404
            } else {
                retVal = (Entry<K,V>)e;
                next = ((Entry<K,V>)e).next;
2405 2406 2407 2408
            }

            if (next == null) { // Move to next bin
                findNextBin();
D
duke 已提交
2409 2410
            }
            current = e;
2411
            return retVal;
D
duke 已提交
2412 2413 2414 2415 2416 2417 2418
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
2419 2420 2421 2422 2423 2424 2425 2426
            K k;

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

            }
D
duke 已提交
2427 2428 2429 2430
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445

        /*
         * 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 已提交
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 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 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
    }

    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();
        }
2516 2517 2518 2519 2520 2521 2522 2523

        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 已提交
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
    }

    /**
     * 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();
        }
2557 2558 2559 2560 2561 2562 2563 2564

        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 已提交
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
    }

    /**
     * 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;
2599
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
D
duke 已提交
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
            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();
        }
2612 2613 2614 2615 2616 2617 2618 2619

        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 已提交
2620 2621 2622 2623 2624 2625 2626
    }

    /**
     * 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
2627
     *             bucket array) is emitted (int), followed by the
D
duke 已提交
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
     *             <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
2640 2641 2642
        if (table==EMPTY_TABLE) {
            s.writeInt(roundUpToPowerOf2(threshold));
        } else {
2643
            s.writeInt(table.length);
2644
        }
D
duke 已提交
2645 2646 2647 2648 2649

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

        // Write out keys and values (alternating)
2650 2651
        if (size > 0) {
            for(Map.Entry<K,V> e : entrySet0()) {
D
duke 已提交
2652 2653 2654 2655 2656 2657 2658 2659 2660
                s.writeObject(e.getKey());
                s.writeObject(e.getValue());
            }
        }
    }

    private static final long serialVersionUID = 362498820763181265L;

    /**
2661
     * Reconstitute the {@code HashMap} instance from a stream (i.e.,
D
duke 已提交
2662 2663 2664 2665 2666
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
2667
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
D
duke 已提交
2668
        s.defaultReadObject();
2669
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
2670 2671
            throw new InvalidObjectException("Illegal load factor: " +
                                               loadFactor);
2672
        }
2673

2674
        // set other fields that need values
2675
        if (Holder.USE_HASHSEED) {
2676
            int seed = ThreadLocalRandom.current().nextInt();
2677
            Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
2678
                                         (seed != 0) ? seed : 1);
2679
        }
2680
        table = EMPTY_TABLE;
D
duke 已提交
2681

2682 2683
        // Read in number of buckets
        s.readInt(); // ignored.
2684 2685 2686 2687 2688 2689 2690

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

2691 2692
        // capacity chosen by number of mappings and desired load (if >= 0.25)
        int capacity = (int) Math.min(
2693 2694 2695
                mappings * Math.min(1 / loadFactor, 4.0f),
                // we have limits...
                HashMap.MAXIMUM_CAPACITY);
2696 2697 2698 2699 2700 2701

        // allocate the bucket array;
        if (mappings > 0) {
            inflateTable(capacity);
        } else {
            threshold = capacity;
2702
        }
D
duke 已提交
2703 2704 2705 2706

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

        // Read the keys and values, and put the mappings in the HashMap
2707
        for (int i=0; i<mappings; i++) {
2708
            @SuppressWarnings("unchecked")
2709
            K key = (K) s.readObject();
2710
            @SuppressWarnings("unchecked")
2711
            V value = (V) s.readObject();
D
duke 已提交
2712 2713 2714 2715 2716 2717 2718
            putForCreate(key, value);
        }
    }

    // These methods are used when serializing HashSets
    int   capacity()     { return table.length; }
    float loadFactor()   { return loadFactor;   }
2719 2720 2721 2722 2723 2724

    /**
     * Standin until HM overhaul; based loosely on Weak and Identity HM.
     */
    static class HashMapSpliterator<K,V> {
        final HashMap<K,V> map;
2725
        Object current;             // current node, can be Entry or TreeNode
2726 2727 2728 2729
        int index;                  // current index, modified on advance/split
        int fence;                  // one past last index
        int est;                    // size estimate
        int expectedModCount;       // for comodification checks
2730 2731 2732 2733 2734 2735
        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.
2736 2737 2738 2739 2740 2741 2742 2743 2744

        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;
2745
            this.acceptedNull = false;
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
        }

        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;
2775 2776 2777 2778 2779 2780 2781 2782 2783
            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;
            }
2784 2785 2786 2787 2788 2789 2790 2791
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
2792
            Object[] tab = m.table;
2793 2794 2795 2796 2797 2798
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
2799 2800 2801 2802 2803 2804 2805

            if (!acceptedNull) {
                acceptedNull = true;
                if (m.nullKeyEntry != null) {
                    action.accept(m.nullKeyEntry.key);
                }
            }
2806 2807
            if (tab.length >= hi && (i = index) >= 0 &&
                (i < (index = hi) || current != null)) {
2808
                Object p = current;
2809
                current = null;
2810
                do {
2811
                    if (p == null) {
2812
                        p = tab[i++];
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
                        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;
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
                    }
                } 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();
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
            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) {
2850
                while (current != null || index < hi) {
2851
                    if (current == null) {
2852
                        current = tab[index++];
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
                        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;
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890
                        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;
2891 2892 2893 2894 2895 2896 2897 2898 2899
            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;
            }
2900 2901 2902 2903 2904 2905 2906 2907
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
2908
            Object[] tab = m.table;
2909 2910 2911 2912 2913 2914
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
2915 2916 2917 2918 2919 2920 2921

            if (!acceptedNull) {
                acceptedNull = true;
                if (m.nullKeyEntry != null) {
                    action.accept(m.nullKeyEntry.value);
                }
            }
2922 2923
            if (tab.length >= hi && (i = index) >= 0 &&
                (i < (index = hi) || current != null)) {
2924
                Object p = current;
2925
                current = null;
2926
                do {
2927
                    if (p == null) {
2928
                        p = tab[i++];
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
                        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;
2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
                    }
                } 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();
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
            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) {
2966
                while (current != null || index < hi) {
2967
                    if (current == null) {
2968
                        current = tab[index++];
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980
                        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;
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
                        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;
3006 3007 3008 3009 3010 3011 3012 3013 3014
            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;
            }
3015 3016 3017 3018 3019 3020 3021 3022
        }

        @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;
3023
            Object[] tab = m.table;
3024 3025 3026 3027 3028 3029
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
3030 3031 3032 3033 3034 3035 3036

            if (!acceptedNull) {
                acceptedNull = true;
                if (m.nullKeyEntry != null) {
                    action.accept(m.nullKeyEntry);
                }
            }
3037 3038
            if (tab.length >= hi && (i = index) >= 0 &&
                (i < (index = hi) || current != null)) {
3039
                Object p = current;
3040
                current = null;
3041
                do {
3042
                    if (p == null) {
3043
                        p = tab[i++];
3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
                        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;

3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068
                    }
                } 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();
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
            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) {
3082
                while (current != null || index < hi) {
3083
                    if (current == null) {
3084
                        current = tab[index++];
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
                        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;
3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
                        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 已提交
3111
}