1 /* 2 * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.util; 27 import java.io.*; 28 29 /** 30 * Hash table based implementation of the <tt>Map</tt> interface. This 31 * implementation provides all of the optional map operations, and permits 32 * <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt> 33 * class is roughly equivalent to <tt>Hashtable</tt>, except that it is 34 * unsynchronized and permits nulls.) This class makes no guarantees as to 35 * the order of the map; in particular, it does not guarantee that the order 36 * will remain constant over time. 37 * 38 * <p>This implementation provides constant-time performance for the basic 39 * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function 40 * disperses the elements properly among the buckets. Iteration over 41 * collection views requires time proportional to the "capacity" of the 42 * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number 43 * of key-value mappings). Thus, it's very important not to set the initial 44 * capacity too high (or the load factor too low) if iteration performance is 45 * important. 46 * 47 * <p>An instance of <tt>HashMap</tt> has two parameters that affect its 48 * performance: <i>initial capacity</i> and <i>load factor</i>. The 49 * <i>capacity</i> is the number of buckets in the hash table, and the initial 50 * capacity is simply the capacity at the time the hash table is created. The 51 * <i>load factor</i> is a measure of how full the hash table is allowed to 52 * get before its capacity is automatically increased. When the number of 53 * entries in the hash table exceeds the product of the load factor and the 54 * current capacity, the hash table is <i>rehashed</i> (that is, internal data 55 * structures are rebuilt) so that the hash table has approximately twice the 56 * number of buckets. 57 * 58 * <p>As a general rule, the default load factor (.75) offers a good tradeoff 59 * between time and space costs. Higher values decrease the space overhead 60 * but increase the lookup cost (reflected in most of the operations of the 61 * <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>). The 62 * expected number of entries in the map and its load factor should be taken 63 * into account when setting its initial capacity, so as to minimize the 64 * number of rehash operations. If the initial capacity is greater 65 * than the maximum number of entries divided by the load factor, no 66 * rehash operations will ever occur. 67 * 68 * <p>If many mappings are to be stored in a <tt>HashMap</tt> instance, 69 * creating it with a sufficiently large capacity will allow the mappings to 70 * be stored more efficiently than letting it perform automatic rehashing as 71 * needed to grow the table. 72 * 73 * <p><strong>Note that this implementation is not synchronized.</strong> 74 * If multiple threads access a hash map concurrently, and at least one of 75 * the threads modifies the map structurally, it <i>must</i> be 76 * synchronized externally. (A structural modification is any operation 77 * that adds or deletes one or more mappings; merely changing the value 78 * associated with a key that an instance already contains is not a 79 * structural modification.) This is typically accomplished by 80 * synchronizing on some object that naturally encapsulates the map. 81 * 82 * If no such object exists, the map should be "wrapped" using the 83 * {@link Collections#synchronizedMap Collections.synchronizedMap} 84 * method. This is best done at creation time, to prevent accidental 85 * unsynchronized access to the map:<pre> 86 * Map m = Collections.synchronizedMap(new HashMap(...));</pre> 87 * 88 * <p>The iterators returned by all of this class's "collection view methods" 89 * are <i>fail-fast</i>: if the map is structurally modified at any time after 90 * the iterator is created, in any way except through the iterator's own 91 * <tt>remove</tt> method, the iterator will throw a 92 * {@link ConcurrentModificationException}. Thus, in the face of concurrent 93 * modification, the iterator fails quickly and cleanly, rather than risking 94 * arbitrary, non-deterministic behavior at an undetermined time in the 95 * future. 96 * 97 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed 98 * as it is, generally speaking, impossible to make any hard guarantees in the 99 * presence of unsynchronized concurrent modification. Fail-fast iterators 100 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. 101 * Therefore, it would be wrong to write a program that depended on this 102 * exception for its correctness: <i>the fail-fast behavior of iterators 103 * should be used only to detect bugs.</i> 104 * 105 * <p>This class is a member of the 106 * <a href="{@docRoot}/../technotes/guides/collections/index.html"> 107 * Java Collections Framework</a>. 108 * 109 * @param <K> the type of keys maintained by this map 110 * @param <V> the type of mapped values 111 * 112 * @author Doug Lea 113 * @author Josh Bloch 114 * @author Arthur van Hoff 115 * @author Neal Gafter 116 * @see Object#hashCode() 117 * @see Collection 118 * @see Map 119 * @see TreeMap 120 * @see Hashtable 121 * @since 1.2 122 */ 123 124 public class HashMap<K,V> 125 extends AbstractMap<K,V> 126 implements Map<K,V>, Cloneable, Serializable 127 { 128 129 /** 130 * The default initial capacity - MUST be a power of two. 131 */ 132 static final int DEFAULT_INITIAL_CAPACITY = 16; 133 134 /** 135 * The maximum capacity, used if a higher value is implicitly specified 136 * by either of the constructors with arguments. 137 * MUST be a power of two <= 1<<30. 138 */ 139 static final int MAXIMUM_CAPACITY = 1 << 30; 140 141 /** 142 * The load factor used when none specified in constructor. 143 */ 144 static final float DEFAULT_LOAD_FACTOR = 0.75f; 145 146 /** 147 * The table, resized as necessary. Length MUST Always be a power of two. 148 */ 149 transient Entry<K,V>[] table; 150 151 /** 152 * The number of key-value mappings contained in this map. 153 */ 154 transient int size; 155 156 /** 157 * The next size value at which to resize (capacity * load factor). 158 * @serial 159 */ 160 int threshold; 161 162 /** 163 * The load factor for the hash table. 164 * 165 * @serial 166 */ 167 final float loadFactor; 168 169 /** 170 * The number of times this HashMap has been structurally modified 171 * Structural modifications are those that change the number of mappings in 172 * the HashMap or otherwise modify its internal structure (e.g., 173 * rehash). This field is used to make iterators on Collection-views of 174 * the HashMap fail-fast. (See ConcurrentModificationException). 175 */ 176 transient int modCount; 177 178 /** 179 * The default threshold of capacity above which alternate hashing is used. 180 * Alternative hashing reduces the incidence of collisions due to weak hash 181 * code calculation. 182 * <p/> 183 * This value may be overridden by defining the system property 184 * {@code java.util.althashing.threshold}. A property value of {@code 1} 185 * forces alternative hashing to be used at all times whereas 186 * {@code 2147483648 } ({@code Integer.MAX_VALUE}) value ensures that 187 * alternative hashing is never used. 188 */ 189 static final int ALTERNATE_HASHING_THRESHOLD_DEFAULT = 512; 190 191 /** 192 * holds values which can't be initialized until after VM is booted. 193 */ 194 private static class Holder { 195 196 // Unsafe mechanics 197 /** 198 * 199 */ 200 static final sun.misc.Unsafe UNSAFE; 201 202 /** 203 * Offset of "final" hashmask field we must set in 204 * readObject() method. 205 */ 206 static final long HASHSEED_OFFSET; 207 208 /** 209 * Table capacity above which to switch to use alternate hashing. 210 */ 211 static final int ALTERNATE_HASHING_THRESHOLD; 212 213 static { 214 String altThreshold = java.security.AccessController.doPrivileged( 215 new sun.security.action.GetPropertyAction( 216 "jdk.map.althashing.threshold")); 217 218 int threshold; 219 try { 220 threshold = (null != altThreshold) 221 ? Integer.parseInt(altThreshold) 222 : ALTERNATE_HASHING_THRESHOLD_DEFAULT; 223 224 if(threshold == -1) { 225 threshold = Integer.MAX_VALUE; 226 } 227 228 if(threshold < 0) { 229 throw new IllegalArgumentException("value must be positive integer."); 230 } 231 } catch(IllegalArgumentException failed) { 232 throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed); 233 } 234 ALTERNATE_HASHING_THRESHOLD = threshold; 235 236 try { 237 UNSAFE = sun.misc.Unsafe.getUnsafe(); 238 HASHSEED_OFFSET = UNSAFE.objectFieldOffset( 239 HashMap.class.getDeclaredField("hashSeed")); 240 } catch (NoSuchFieldException | SecurityException e) { 241 throw new Error("Failed to record hashSeed offset", e); 242 } 243 } 244 } 245 246 /** 247 * If {@code true} then perform alternate hashing to reduce the incidence of 248 * collisions due to weak hash code calculation. 249 */ 250 transient boolean useAltHashing; 251 252 /** 253 * A randomizing value associated with this instance that is applied to 254 * hash code of keys to make hash collisions harder to find. 255 */ 256 transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this); 257 258 /** 259 * Constructs an empty <tt>HashMap</tt> with the specified initial 260 * capacity and load factor. 261 * 262 * @param initialCapacity the initial capacity 263 * @param loadFactor the load factor 264 * @throws IllegalArgumentException if the initial capacity is negative 265 * or the load factor is nonpositive 266 */ 267 public HashMap(int initialCapacity, float loadFactor) { 268 if (initialCapacity < 0) 269 throw new IllegalArgumentException("Illegal initial capacity: " + 270 initialCapacity); 271 if (initialCapacity > MAXIMUM_CAPACITY) 272 initialCapacity = MAXIMUM_CAPACITY; 273 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 274 throw new IllegalArgumentException("Illegal load factor: " + 275 loadFactor); 276 277 // Find a power of 2 >= initialCapacity 278 int capacity = 1; 279 while (capacity < initialCapacity) 280 capacity <<= 1; 281 282 this.loadFactor = loadFactor; 283 threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); 284 table = new Entry[capacity]; 285 useAltHashing = sun.misc.VM.isBooted() && 286 (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD); 287 init(); 288 } 289 290 /** 291 * Constructs an empty <tt>HashMap</tt> with the specified initial 292 * capacity and the default load factor (0.75). 293 * 294 * @param initialCapacity the initial capacity. 295 * @throws IllegalArgumentException if the initial capacity is negative. 296 */ 297 public HashMap(int initialCapacity) { 298 this(initialCapacity, DEFAULT_LOAD_FACTOR); 299 } 300 301 /** 302 * Constructs an empty <tt>HashMap</tt> with the default initial capacity 303 * (16) and the default load factor (0.75). 304 */ 305 public HashMap() { 306 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); 307 } 308 309 /** 310 * Constructs a new <tt>HashMap</tt> with the same mappings as the 311 * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with 312 * default load factor (0.75) and an initial capacity sufficient to 313 * hold the mappings in the specified <tt>Map</tt>. 314 * 315 * @param m the map whose mappings are to be placed in this map 316 * @throws NullPointerException if the specified map is null 317 */ 318 public HashMap(Map<? extends K, ? extends V> m) { 319 this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, 320 DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR); 321 putAllForCreate(m); 322 } 323 324 // internal utilities 325 326 /** 327 * Initialization hook for subclasses. This method is called 328 * in all constructors and pseudo-constructors (clone, readObject) 329 * after HashMap has been initialized but before any entries have 330 * been inserted. (In the absence of this method, readObject would 331 * require explicit knowledge of subclasses.) 332 */ 333 void init() { 334 } 335 336 /** 337 * Retrieve object hash code and applies a supplemental hash function to the 338 * result hash, which defends against poor quality hash functions. This is 339 * critical because HashMap uses power-of-two length hash tables, that 340 * otherwise encounter collisions for hashCodes that do not differ 341 * in lower bits. Note: Null keys always map to hash 0, thus index 0. 342 */ 343 final int hash(Object k) { 344 int h = 0; 345 if (useAltHashing) { 346 if (k instanceof String) { 347 return sun.misc.Hashing.stringHash32((String) k); 348 } 349 h = hashSeed; 350 } 351 352 h ^= k.hashCode(); 353 354 // This function ensures that hashCodes that differ only by 355 // constant multiples at each bit position have a bounded 356 // number of collisions (approximately 8 at default load factor). 357 h ^= (h >>> 20) ^ (h >>> 12); 358 return h ^ (h >>> 7) ^ (h >>> 4); 359 } 360 361 /** 362 * Returns index for hash code h. 363 */ 364 static int indexFor(int h, int length) { 365 return h & (length-1); 366 } 367 368 /** 369 * Returns the number of key-value mappings in this map. 370 * 371 * @return the number of key-value mappings in this map 372 */ 373 public int size() { 374 return size; 375 } 376 377 /** 378 * Returns <tt>true</tt> if this map contains no key-value mappings. 379 * 380 * @return <tt>true</tt> if this map contains no key-value mappings 381 */ 382 public boolean isEmpty() { 383 return size == 0; 384 } 385 386 /** 387 * Returns the value to which the specified key is mapped, 388 * or {@code null} if this map contains no mapping for the key. 389 * 390 * <p>More formally, if this map contains a mapping from a key 391 * {@code k} to a value {@code v} such that {@code (key==null ? k==null : 392 * key.equals(k))}, then this method returns {@code v}; otherwise 393 * it returns {@code null}. (There can be at most one such mapping.) 394 * 395 * <p>A return value of {@code null} does not <i>necessarily</i> 396 * indicate that the map contains no mapping for the key; it's also 397 * possible that the map explicitly maps the key to {@code null}. 398 * The {@link #containsKey containsKey} operation may be used to 399 * distinguish these two cases. 400 * 401 * @see #put(Object, Object) 402 */ 403 public V get(Object key) { 404 if (key == null) 405 return getForNullKey(); 406 Entry<K,V> entry = getEntry(key); 407 408 return null == entry ? null : entry.getValue(); 409 } 410 411 /** 412 * Offloaded version of get() to look up null keys. Null keys map 413 * to index 0. This null case is split out into separate methods 414 * for the sake of performance in the two most commonly used 415 * operations (get and put), but incorporated with conditionals in 416 * others. 417 */ 418 private V getForNullKey() { 419 for (Entry<K,V> e = table[0]; e != null; e = e.next) { 420 if (e.key == null) 421 return e.value; 422 } 423 return null; 424 } 425 426 /** 427 * Returns <tt>true</tt> if this map contains a mapping for the 428 * specified key. 429 * 430 * @param key The key whose presence in this map is to be tested 431 * @return <tt>true</tt> if this map contains a mapping for the specified 432 * key. 433 */ 434 public boolean containsKey(Object key) { 435 return getEntry(key) != null; 436 } 437 438 /** 439 * Returns the entry associated with the specified key in the 440 * HashMap. Returns null if the HashMap contains no mapping 441 * for the key. 442 */ 443 final Entry<K,V> getEntry(Object key) { 444 int hash = (key == null) ? 0 : hash(key); 445 for (Entry<K,V> e = table[indexFor(hash, table.length)]; 446 e != null; 447 e = e.next) { 448 Object k; 449 if (e.hash == hash && 450 ((k = e.key) == key || (key != null && key.equals(k)))) 451 return e; 452 } 453 return null; 454 } 455 456 457 /** 458 * Associates the specified value with the specified key in this map. 459 * If the map previously contained a mapping for the key, the old 460 * value is replaced. 461 * 462 * @param key key with which the specified value is to be associated 463 * @param value value to be associated with the specified key 464 * @return the previous value associated with <tt>key</tt>, or 465 * <tt>null</tt> if there was no mapping for <tt>key</tt>. 466 * (A <tt>null</tt> return can also indicate that the map 467 * previously associated <tt>null</tt> with <tt>key</tt>.) 468 */ 469 public V put(K key, V value) { 470 if (key == null) 471 return putForNullKey(value); 472 int hash = hash(key); 473 int i = indexFor(hash, table.length); 474 for (Entry<K,V> e = table[i]; e != null; e = e.next) { 475 Object k; 476 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 477 V oldValue = e.value; 478 e.value = value; 479 e.recordAccess(this); 480 return oldValue; 481 } 482 } 483 484 modCount++; 485 addEntry(hash, key, value, i); 486 return null; 487 } 488 489 /** 490 * Offloaded version of put for null keys 491 */ 492 private V putForNullKey(V value) { 493 for (Entry<K,V> e = table[0]; e != null; e = e.next) { 494 if (e.key == null) { 495 V oldValue = e.value; 496 e.value = value; 497 e.recordAccess(this); 498 return oldValue; 499 } 500 } 501 modCount++; 502 addEntry(0, null, value, 0); 503 return null; 504 } 505 506 /** 507 * This method is used instead of put by constructors and 508 * pseudoconstructors (clone, readObject). It does not resize the table, 509 * check for comodification, etc. It calls createEntry rather than 510 * addEntry. 511 */ 512 private void putForCreate(K key, V value) { 513 int hash = null == key ? 0 : hash(key); 514 int i = indexFor(hash, table.length); 515 516 /** 517 * Look for preexisting entry for key. This will never happen for 518 * clone or deserialize. It will only happen for construction if the 519 * input Map is a sorted map whose ordering is inconsistent w/ equals. 520 */ 521 for (Entry<K,V> e = table[i]; e != null; e = e.next) { 522 Object k; 523 if (e.hash == hash && 524 ((k = e.key) == key || (key != null && key.equals(k)))) { 525 e.value = value; 526 return; 527 } 528 } 529 530 createEntry(hash, key, value, i); 531 } 532 533 private void putAllForCreate(Map<? extends K, ? extends V> m) { 534 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) 535 putForCreate(e.getKey(), e.getValue()); 536 } 537 538 /** 539 * Rehashes the contents of this map into a new array with a 540 * larger capacity. This method is called automatically when the 541 * number of keys in this map reaches its threshold. 542 * 543 * If current capacity is MAXIMUM_CAPACITY, this method does not 544 * resize the map, but sets threshold to Integer.MAX_VALUE. 545 * This has the effect of preventing future calls. 546 * 547 * @param newCapacity the new capacity, MUST be a power of two; 548 * must be greater than current capacity unless current 549 * capacity is MAXIMUM_CAPACITY (in which case value 550 * is irrelevant). 551 */ 552 void resize(int newCapacity) { 553 Entry[] oldTable = table; 554 int oldCapacity = oldTable.length; 555 if (oldCapacity == MAXIMUM_CAPACITY) { 556 threshold = Integer.MAX_VALUE; 557 return; 558 } 559 560 Entry[] newTable = new Entry[newCapacity]; 561 boolean oldAltHashing = useAltHashing; 562 useAltHashing |= sun.misc.VM.isBooted() && 563 (newCapacity >= Holder.ALTERNATE_HASHING_THRESHOLD); 564 boolean rehash = oldAltHashing ^ useAltHashing; 565 transfer(newTable, rehash); 566 table = newTable; 567 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); 568 } 569 570 /** 571 * Transfers all entries from current table to newTable. 572 */ 573 void transfer(Entry[] newTable, boolean rehash) { 574 int newCapacity = newTable.length; 575 for (Entry<K,V> e : table) { 576 while(null != e) { 577 Entry<K,V> next = e.next; 578 if(rehash) { 579 e.hash = null == e.key ? 0 : hash(e.key); 580 } 581 int i = indexFor(e.hash, newCapacity); 582 e.next = newTable[i]; 583 newTable[i] = e; 584 e = next; 585 } 586 } 587 } 588 589 /** 590 * Copies all of the mappings from the specified map to this map. 591 * These mappings will replace any mappings that this map had for 592 * any of the keys currently in the specified map. 593 * 594 * @param m mappings to be stored in this map 595 * @throws NullPointerException if the specified map is null 596 */ 597 public void putAll(Map<? extends K, ? extends V> m) { 598 int numKeysToBeAdded = m.size(); 599 if (numKeysToBeAdded == 0) 600 return; 601 602 /* 603 * Expand the map if the map if the number of mappings to be added 604 * is greater than or equal to threshold. This is conservative; the 605 * obvious condition is (m.size() + size) >= threshold, but this 606 * condition could result in a map with twice the appropriate capacity, 607 * if the keys to be added overlap with the keys already in this map. 608 * By using the conservative calculation, we subject ourself 609 * to at most one extra resize. 610 */ 611 if (numKeysToBeAdded > threshold) { 612 int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1); 613 if (targetCapacity > MAXIMUM_CAPACITY) 614 targetCapacity = MAXIMUM_CAPACITY; 615 int newCapacity = table.length; 616 while (newCapacity < targetCapacity) 617 newCapacity <<= 1; 618 if (newCapacity > table.length) 619 resize(newCapacity); 620 } 621 622 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) 623 put(e.getKey(), e.getValue()); 624 } 625 626 /** 627 * Removes the mapping for the specified key from this map if present. 628 * 629 * @param key key whose mapping is to be removed from the map 630 * @return the previous value associated with <tt>key</tt>, or 631 * <tt>null</tt> if there was no mapping for <tt>key</tt>. 632 * (A <tt>null</tt> return can also indicate that the map 633 * previously associated <tt>null</tt> with <tt>key</tt>.) 634 */ 635 public V remove(Object key) { 636 Entry<K,V> e = removeEntryForKey(key); 637 return (e == null ? null : e.value); 638 } 639 640 /** 641 * Removes and returns the entry associated with the specified key 642 * in the HashMap. Returns null if the HashMap contains no mapping 643 * for this key. 644 */ 645 final Entry<K,V> removeEntryForKey(Object key) { 646 int hash = (key == null) ? 0 : hash(key); 647 int i = indexFor(hash, table.length); 648 Entry<K,V> prev = table[i]; 649 Entry<K,V> e = prev; 650 651 while (e != null) { 652 Entry<K,V> next = e.next; 653 Object k; 654 if (e.hash == hash && 655 ((k = e.key) == key || (key != null && key.equals(k)))) { 656 modCount++; 657 size--; 658 if (prev == e) 659 table[i] = next; 660 else 661 prev.next = next; 662 e.recordRemoval(this); 663 return e; 664 } 665 prev = e; 666 e = next; 667 } 668 669 return e; 670 } 671 672 /** 673 * Special version of remove for EntrySet using {@code Map.Entry.equals()} 674 * for matching. 675 */ 676 final Entry<K,V> removeMapping(Object o) { 677 if (!(o instanceof Map.Entry)) 678 return null; 679 680 Map.Entry<K,V> entry = (Map.Entry<K,V>) o; 681 Object key = entry.getKey(); 682 int hash = (key == null) ? 0 : hash(key.hashCode()); 683 int i = indexFor(hash, table.length); 684 Entry<K,V> prev = table[i]; 685 Entry<K,V> e = prev; 686 687 while (e != null) { 688 Entry<K,V> next = e.next; 689 if (e.hash == hash && e.equals(entry)) { 690 modCount++; 691 size--; 692 if (prev == e) 693 table[i] = next; 694 else 695 prev.next = next; 696 e.recordRemoval(this); 697 return e; 698 } 699 prev = e; 700 e = next; 701 } 702 703 return e; 704 } 705 706 /** 707 * Removes all of the mappings from this map. 708 * The map will be empty after this call returns. 709 */ 710 public void clear() { 711 modCount++; 712 Entry[] tab = table; 713 for (int i = 0; i < tab.length; i++) 714 tab[i] = null; 715 size = 0; 716 } 717 718 /** 719 * Returns <tt>true</tt> if this map maps one or more keys to the 720 * specified value. 721 * 722 * @param value value whose presence in this map is to be tested 723 * @return <tt>true</tt> if this map maps one or more keys to the 724 * specified value 725 */ 726 public boolean containsValue(Object value) { 727 if (value == null) 728 return containsNullValue(); 729 730 Entry[] tab = table; 731 for (int i = 0; i < tab.length ; i++) 732 for (Entry e = tab[i] ; e != null ; e = e.next) 733 if (value.equals(e.value)) 734 return true; 735 return false; 736 } 737 738 /** 739 * Special-case code for containsValue with null argument 740 */ 741 private boolean containsNullValue() { 742 Entry[] tab = table; 743 for (int i = 0; i < tab.length ; i++) 744 for (Entry e = tab[i] ; e != null ; e = e.next) 745 if (e.value == null) 746 return true; 747 return false; 748 } 749 750 /** 751 * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and 752 * values themselves are not cloned. 753 * 754 * @return a shallow copy of this map 755 */ 756 public Object clone() { 757 HashMap<K,V> result = null; 758 try { 759 result = (HashMap<K,V>)super.clone(); 760 } catch (CloneNotSupportedException e) { 761 // assert false; 762 } 763 result.table = new Entry[table.length]; 764 result.entrySet = null; 765 result.modCount = 0; 766 result.size = 0; 767 result.init(); 768 result.putAllForCreate(this); 769 770 return result; 771 } 772 773 static class Entry<K,V> implements Map.Entry<K,V> { 774 final K key; 775 V value; 776 Entry<K,V> next; 777 int hash; 778 779 /** 780 * Creates new entry. 781 */ 782 Entry(int h, K k, V v, Entry<K,V> n) { 783 value = v; 784 next = n; 785 key = k; 786 hash = h; 787 } 788 789 public final K getKey() { 790 return key; 791 } 792 793 public final V getValue() { 794 return value; 795 } 796 797 public final V setValue(V newValue) { 798 V oldValue = value; 799 value = newValue; 800 return oldValue; 801 } 802 803 public final boolean equals(Object o) { 804 if (!(o instanceof Map.Entry)) 805 return false; 806 Map.Entry e = (Map.Entry)o; 807 Object k1 = getKey(); 808 Object k2 = e.getKey(); 809 if (k1 == k2 || (k1 != null && k1.equals(k2))) { 810 Object v1 = getValue(); 811 Object v2 = e.getValue(); 812 if (v1 == v2 || (v1 != null && v1.equals(v2))) 813 return true; 814 } 815 return false; 816 } 817 818 public final int hashCode() { 819 return (key==null ? 0 : key.hashCode()) ^ 820 (value==null ? 0 : value.hashCode()); 821 } 822 823 public final String toString() { 824 return getKey() + "=" + getValue(); 825 } 826 827 /** 828 * This method is invoked whenever the value in an entry is 829 * overwritten by an invocation of put(k,v) for a key k that's already 830 * in the HashMap. 831 */ 832 void recordAccess(HashMap<K,V> m) { 833 } 834 835 /** 836 * This method is invoked whenever the entry is 837 * removed from the table. 838 */ 839 void recordRemoval(HashMap<K,V> m) { 840 } 841 } 842 843 /** 844 * Adds a new entry with the specified key, value and hash code to 845 * the specified bucket. It is the responsibility of this 846 * method to resize the table if appropriate. 847 * 848 * Subclass overrides this to alter the behavior of put method. 849 */ 850 void addEntry(int hash, K key, V value, int bucketIndex) { 851 if ((size >= threshold) && (null != table[bucketIndex])) { 852 resize(2 * table.length); 853 hash = (null != key) ? hash(key) : 0; 854 bucketIndex = indexFor(hash, table.length); 855 } 856 857 createEntry(hash, key, value, bucketIndex); 858 } 859 860 /** 861 * Like addEntry except that this version is used when creating entries 862 * as part of Map construction or "pseudo-construction" (cloning, 863 * deserialization). This version needn't worry about resizing the table. 864 * 865 * Subclass overrides this to alter the behavior of HashMap(Map), 866 * clone, and readObject. 867 */ 868 void createEntry(int hash, K key, V value, int bucketIndex) { 869 Entry<K,V> e = table[bucketIndex]; 870 table[bucketIndex] = new Entry<>(hash, key, value, e); 871 size++; 872 } 873 874 private abstract class HashIterator<E> implements Iterator<E> { 875 Entry<K,V> next; // next entry to return 876 int expectedModCount; // For fast-fail 877 int index; // current slot 878 Entry<K,V> current; // current entry 879 880 HashIterator() { 881 expectedModCount = modCount; 882 if (size > 0) { // advance to first entry 883 Entry[] t = table; 884 while (index < t.length && (next = t[index++]) == null) 885 ; 886 } 887 } 888 889 public final boolean hasNext() { 890 return next != null; 891 } 892 893 final Entry<K,V> nextEntry() { 894 if (modCount != expectedModCount) 895 throw new ConcurrentModificationException(); 896 Entry<K,V> e = next; 897 if (e == null) 898 throw new NoSuchElementException(); 899 900 if ((next = e.next) == null) { 901 Entry[] t = table; 902 while (index < t.length && (next = t[index++]) == null) 903 ; 904 } 905 current = e; 906 return e; 907 } 908 909 public void remove() { 910 if (current == null) 911 throw new IllegalStateException(); 912 if (modCount != expectedModCount) 913 throw new ConcurrentModificationException(); 914 Object k = current.key; 915 current = null; 916 HashMap.this.removeEntryForKey(k); 917 expectedModCount = modCount; 918 } 919 } 920 921 private final class ValueIterator extends HashIterator<V> { 922 public V next() { 923 return nextEntry().value; 924 } 925 } 926 927 private final class KeyIterator extends HashIterator<K> { 928 public K next() { 929 return nextEntry().getKey(); 930 } 931 } 932 933 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> { 934 public Map.Entry<K,V> next() { 935 return nextEntry(); 936 } 937 } 938 939 // Subclass overrides these to alter behavior of views' iterator() method 940 Iterator<K> newKeyIterator() { 941 return new KeyIterator(); 942 } 943 Iterator<V> newValueIterator() { 944 return new ValueIterator(); 945 } 946 Iterator<Map.Entry<K,V>> newEntryIterator() { 947 return new EntryIterator(); 948 } 949 950 951 // Views 952 953 private transient Set<Map.Entry<K,V>> entrySet = null; 954 955 /** 956 * Returns a {@link Set} view of the keys contained in this map. 957 * The set is backed by the map, so changes to the map are 958 * reflected in the set, and vice-versa. If the map is modified 959 * while an iteration over the set is in progress (except through 960 * the iterator's own <tt>remove</tt> operation), the results of 961 * the iteration are undefined. The set supports element removal, 962 * which removes the corresponding mapping from the map, via the 963 * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, 964 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> 965 * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> 966 * operations. 967 */ 968 public Set<K> keySet() { 969 Set<K> ks = keySet; 970 return (ks != null ? ks : (keySet = new KeySet())); 971 } 972 973 private final class KeySet extends AbstractSet<K> { 974 public Iterator<K> iterator() { 975 return newKeyIterator(); 976 } 977 public int size() { 978 return size; 979 } 980 public boolean contains(Object o) { 981 return containsKey(o); 982 } 983 public boolean remove(Object o) { 984 return HashMap.this.removeEntryForKey(o) != null; 985 } 986 public void clear() { 987 HashMap.this.clear(); 988 } 989 } 990 991 /** 992 * Returns a {@link Collection} view of the values contained in this map. 993 * The collection is backed by the map, so changes to the map are 994 * reflected in the collection, and vice-versa. If the map is 995 * modified while an iteration over the collection is in progress 996 * (except through the iterator's own <tt>remove</tt> operation), 997 * the results of the iteration are undefined. The collection 998 * supports element removal, which removes the corresponding 999 * mapping from the map, via the <tt>Iterator.remove</tt>, 1000 * <tt>Collection.remove</tt>, <tt>removeAll</tt>, 1001 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not 1002 * support the <tt>add</tt> or <tt>addAll</tt> operations. 1003 */ 1004 public Collection<V> values() { 1005 Collection<V> vs = values; 1006 return (vs != null ? vs : (values = new Values())); 1007 } 1008 1009 private final class Values extends AbstractCollection<V> { 1010 public Iterator<V> iterator() { 1011 return newValueIterator(); 1012 } 1013 public int size() { 1014 return size; 1015 } 1016 public boolean contains(Object o) { 1017 return containsValue(o); 1018 } 1019 public void clear() { 1020 HashMap.this.clear(); 1021 } 1022 } 1023 1024 /** 1025 * Returns a {@link Set} view of the mappings contained in this map. 1026 * The set is backed by the map, so changes to the map are 1027 * reflected in the set, and vice-versa. If the map is modified 1028 * while an iteration over the set is in progress (except through 1029 * the iterator's own <tt>remove</tt> operation, or through the 1030 * <tt>setValue</tt> operation on a map entry returned by the 1031 * iterator) the results of the iteration are undefined. The set 1032 * supports element removal, which removes the corresponding 1033 * mapping from the map, via the <tt>Iterator.remove</tt>, 1034 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and 1035 * <tt>clear</tt> operations. It does not support the 1036 * <tt>add</tt> or <tt>addAll</tt> operations. 1037 * 1038 * @return a set view of the mappings contained in this map 1039 */ 1040 public Set<Map.Entry<K,V>> entrySet() { 1041 return entrySet0(); 1042 } 1043 1044 private Set<Map.Entry<K,V>> entrySet0() { 1045 Set<Map.Entry<K,V>> es = entrySet; 1046 return es != null ? es : (entrySet = new EntrySet()); 1047 } 1048 1049 private final class EntrySet extends AbstractSet<Map.Entry<K,V>> { 1050 public Iterator<Map.Entry<K,V>> iterator() { 1051 return newEntryIterator(); 1052 } 1053 public boolean contains(Object o) { 1054 if (!(o instanceof Map.Entry)) 1055 return false; 1056 Map.Entry<K,V> e = (Map.Entry<K,V>) o; 1057 Entry<K,V> candidate = getEntry(e.getKey()); 1058 return candidate != null && candidate.equals(e); 1059 } 1060 public boolean remove(Object o) { 1061 return removeMapping(o) != null; 1062 } 1063 public int size() { 1064 return size; 1065 } 1066 public void clear() { 1067 HashMap.this.clear(); 1068 } 1069 } 1070 1071 /** 1072 * Save the state of the <tt>HashMap</tt> instance to a stream (i.e., 1073 * serialize it). 1074 * 1075 * @serialData The <i>capacity</i> of the HashMap (the length of the 1076 * bucket array) is emitted (int), followed by the 1077 * <i>size</i> (an int, the number of key-value 1078 * mappings), followed by the key (Object) and value (Object) 1079 * for each key-value mapping. The key-value mappings are 1080 * emitted in no particular order. 1081 */ 1082 private void writeObject(java.io.ObjectOutputStream s) 1083 throws IOException 1084 { 1085 Iterator<Map.Entry<K,V>> i = 1086 (size > 0) ? entrySet0().iterator() : null; 1087 1088 // Write out the threshold, loadfactor, and any hidden stuff 1089 s.defaultWriteObject(); 1090 1091 // Write out number of buckets 1092 s.writeInt(table.length); 1093 1094 // Write out size (number of Mappings) 1095 s.writeInt(size); 1096 1097 // Write out keys and values (alternating) 1098 if (size > 0) { 1099 for(Map.Entry<K,V> e : entrySet0()) { 1100 s.writeObject(e.getKey()); 1101 s.writeObject(e.getValue()); 1102 } 1103 } 1104 } 1105 1106 private static final long serialVersionUID = 362498820763181265L; 1107 1108 /** 1109 * Reconstitute the {@code HashMap} instance from a stream (i.e., 1110 * deserialize it). 1111 */ 1112 private void readObject(java.io.ObjectInputStream s) 1113 throws IOException, ClassNotFoundException 1114 { 1115 // Read in the threshold (ignored), loadfactor, and any hidden stuff 1116 s.defaultReadObject(); 1117 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 1118 throw new InvalidObjectException("Illegal load factor: " + 1119 loadFactor); 1120 1121 // set hashSeed (can only happen after VM boot) 1122 Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET, 1123 sun.misc.Hashing.randomHashSeed(this)); 1124 1125 // Read in number of buckets and allocate the bucket array; 1126 s.readInt(); // ignored 1127 1128 // Read number of mappings 1129 int mappings = s.readInt(); 1130 if (mappings < 0) 1131 throw new InvalidObjectException("Illegal mappings count: " + 1132 mappings); 1133 1134 int initialCapacity = (int) Math.min( 1135 // capacity chosen by number of mappings 1136 // and desired load (if >= 0.25) 1137 mappings * Math.min(1 / loadFactor, 4.0f), 1138 // we have limits... 1139 HashMap.MAXIMUM_CAPACITY); 1140 int capacity = 1; 1141 // find smallest power of two which holds all mappings 1142 while (capacity < initialCapacity) { 1143 capacity <<= 1; 1144 } 1145 1146 table = new Entry[capacity]; 1147 threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); 1148 useAltHashing = sun.misc.VM.isBooted() && 1149 (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD); 1150 1151 init(); // Give subclass a chance to do its thing. 1152 1153 // Read the keys and values, and put the mappings in the HashMap 1154 for (int i=0; i<mappings; i++) { 1155 K key = (K) s.readObject(); 1156 V value = (V) s.readObject(); 1157 putForCreate(key, value); 1158 } 1159 } 1160 1161 // These methods are used when serializing HashSets 1162 int capacity() { return table.length; } 1163 float loadFactor() { return loadFactor; } 1164 }