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<?,?>[] 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 private static class Holder { 179 /** 180 * 181 */ 182 static final sun.misc.Unsafe UNSAFE; 183 184 /** 185 * Offset of "final" hashSeed field we must set in 186 * readObject() method. 187 */ 188 static final long HASHSEED_OFFSET; 189 190 static { 191 try { 192 UNSAFE = sun.misc.Unsafe.getUnsafe(); 193 HASHSEED_OFFSET = UNSAFE.objectFieldOffset( 194 HashMap.class.getDeclaredField("hashSeed")); 195 } catch (NoSuchFieldException | SecurityException e) { 196 throw new InternalError("Failed to record hashSeed offset", e); 197 } 198 } 199 } 200 201 /** 202 * A randomizing value associated with this instance that is applied to 203 * hash code of keys to make hash collisions harder to find. 204 */ 205 transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this); 206 207 /** 208 * Constructs an empty <tt>HashMap</tt> with the specified initial 209 * capacity and load factor. 210 * 211 * @param initialCapacity the initial capacity 212 * @param loadFactor the load factor 213 * @throws IllegalArgumentException if the initial capacity is negative 214 * or the load factor is nonpositive 215 */ 216 public HashMap(int initialCapacity, float loadFactor) { 217 if (initialCapacity < 0) 218 throw new IllegalArgumentException("Illegal initial capacity: " + 219 initialCapacity); 220 if (initialCapacity > MAXIMUM_CAPACITY) 221 initialCapacity = MAXIMUM_CAPACITY; 222 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 223 throw new IllegalArgumentException("Illegal load factor: " + 224 loadFactor); 225 226 // Find a power of 2 >= initialCapacity 227 int capacity = 1; 228 while (capacity < initialCapacity) 229 capacity <<= 1; 230 231 this.loadFactor = loadFactor; 232 threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); 233 table = new Entry[capacity]; 234 init(); 235 } 236 237 /** 238 * Constructs an empty <tt>HashMap</tt> with the specified initial 239 * capacity and the default load factor (0.75). 240 * 241 * @param initialCapacity the initial capacity. 242 * @throws IllegalArgumentException if the initial capacity is negative. 243 */ 244 public HashMap(int initialCapacity) { 245 this(initialCapacity, DEFAULT_LOAD_FACTOR); 246 } 247 248 /** 249 * Constructs an empty <tt>HashMap</tt> with the default initial capacity 250 * (16) and the default load factor (0.75). 251 */ 252 public HashMap() { 253 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); 254 } 255 256 /** 257 * Constructs a new <tt>HashMap</tt> with the same mappings as the 258 * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with 259 * default load factor (0.75) and an initial capacity sufficient to 260 * hold the mappings in the specified <tt>Map</tt>. 261 * 262 * @param m the map whose mappings are to be placed in this map 263 * @throws NullPointerException if the specified map is null 264 */ 265 public HashMap(Map<? extends K, ? extends V> m) { 266 this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, 267 DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR); 268 putAllForCreate(m); 269 } 270 271 // internal utilities 272 273 /** 274 * Initialization hook for subclasses. This method is called 275 * in all constructors and pseudo-constructors (clone, readObject) 276 * after HashMap has been initialized but before any entries have 277 * been inserted. (In the absence of this method, readObject would 278 * require explicit knowledge of subclasses.) 279 */ 280 void init() { 281 } 282 283 /** 284 * Retrieve object hash code and applies a supplemental hash function to the 285 * result hash, which defends against poor quality hash functions. This is 286 * critical because HashMap uses power-of-two length hash tables, that 287 * otherwise encounter collisions for hashCodes that do not differ 288 * in lower bits. 289 */ 290 final int hash(Object k) { 291 if (k instanceof String) { 292 return ((String) k).hash32(); 293 } 294 int h = hashSeed ^ k.hashCode(); 295 296 // This function ensures that hashCodes that differ only by 297 // constant multiples at each bit position have a bounded 298 // number of collisions (approximately 8 at default load factor). 299 h ^= (h >>> 20) ^ (h >>> 12); 300 return h ^ (h >>> 7) ^ (h >>> 4); 301 } 302 303 /** 304 * Returns index for hash code h. 305 */ 306 static int indexFor(int h, int length) { 307 return h & (length-1); 308 } 309 310 /** 311 * Returns the number of key-value mappings in this map. 312 * 313 * @return the number of key-value mappings in this map 314 */ 315 public int size() { 316 return size; 317 } 318 319 /** 320 * Returns <tt>true</tt> if this map contains no key-value mappings. 321 * 322 * @return <tt>true</tt> if this map contains no key-value mappings 323 */ 324 public boolean isEmpty() { 325 return size == 0; 326 } 327 328 /** 329 * Returns the value to which the specified key is mapped, 330 * or {@code null} if this map contains no mapping for the key. 331 * 332 * <p>More formally, if this map contains a mapping from a key 333 * {@code k} to a value {@code v} such that {@code (key==null ? k==null : 334 * key.equals(k))}, then this method returns {@code v}; otherwise 335 * it returns {@code null}. (There can be at most one such mapping.) 336 * 337 * <p>A return value of {@code null} does not <i>necessarily</i> 338 * indicate that the map contains no mapping for the key; it's also 339 * possible that the map explicitly maps the key to {@code null}. 340 * The {@link #containsKey containsKey} operation may be used to 341 * distinguish these two cases. 342 * 343 * @see #put(Object, Object) 344 */ 345 @SuppressWarnings("unchecked") 346 public V get(Object key) { 347 Entry<K,V> entry = getEntry(key); 348 349 return null == entry ? null : entry.getValue(); 350 } 351 352 /** 353 * Returns <tt>true</tt> if this map contains a mapping for the 354 * specified key. 355 * 356 * @param key The key whose presence in this map is to be tested 357 * @return <tt>true</tt> if this map contains a mapping for the specified 358 * key. 359 */ 360 public boolean containsKey(Object key) { 361 return getEntry(key) != null; 362 } 363 364 /** 365 * Returns the entry associated with the specified key in the 366 * HashMap. Returns null if the HashMap contains no mapping 367 * for the key. 368 */ 369 @SuppressWarnings("unchecked") 370 final Entry<K,V> getEntry(Object key) { 371 int hash = (key == null) ? 0 : hash(key); 372 for (Entry<?,?> e = table[indexFor(hash, table.length)]; 373 e != null; 374 e = e.next) { 375 Object k; 376 if (e.hash == hash && 377 ((k = e.key) == key || (key != null && key.equals(k)))) 378 return (Entry<K,V>)e; 379 } 380 return null; 381 } 382 383 384 /** 385 * Associates the specified value with the specified key in this map. 386 * If the map previously contained a mapping for the key, the old 387 * value is replaced. 388 * 389 * @param key key with which the specified value is to be associated 390 * @param value value to be associated with the specified key 391 * @return the previous value associated with <tt>key</tt>, or 392 * <tt>null</tt> if there was no mapping for <tt>key</tt>. 393 * (A <tt>null</tt> return can also indicate that the map 394 * previously associated <tt>null</tt> with <tt>key</tt>.) 395 */ 396 public V put(K key, V value) { 397 if (key == null) 398 return putForNullKey(value); 399 int hash = hash(key); 400 int i = indexFor(hash, table.length); 401 @SuppressWarnings("unchecked") 402 Entry<K,V> e = (Entry<K,V>)table[i]; 403 for(; e != null; e = e.next) { 404 Object k; 405 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 406 V oldValue = e.value; 407 e.value = value; 408 e.recordAccess(this); 409 return oldValue; 410 } 411 } 412 413 modCount++; 414 addEntry(hash, key, value, i); 415 return null; 416 } 417 418 /** 419 * Offloaded version of put for null keys 420 */ 421 private V putForNullKey(V value) { 422 @SuppressWarnings("unchecked") 423 Entry<K,V> e = (Entry<K,V>)table[0]; 424 for(; e != null; e = e.next) { 425 if (e.key == null) { 426 V oldValue = e.value; 427 e.value = value; 428 e.recordAccess(this); 429 return oldValue; 430 } 431 } 432 modCount++; 433 addEntry(0, null, value, 0); 434 return null; 435 } 436 437 /** 438 * This method is used instead of put by constructors and 439 * pseudoconstructors (clone, readObject). It does not resize the table, 440 * check for comodification, etc. It calls createEntry rather than 441 * addEntry. 442 */ 443 private void putForCreate(K key, V value) { 444 int hash = null == key ? 0 : hash(key); 445 int i = indexFor(hash, table.length); 446 447 /** 448 * Look for preexisting entry for key. This will never happen for 449 * clone or deserialize. It will only happen for construction if the 450 * input Map is a sorted map whose ordering is inconsistent w/ equals. 451 */ 452 for (@SuppressWarnings("unchecked") 453 Entry<?,V> e = (Entry<?,V>)table[i]; e != null; e = e.next) { 454 Object k; 455 if (e.hash == hash && 456 ((k = e.key) == key || (key != null && key.equals(k)))) { 457 e.value = value; 458 return; 459 } 460 } 461 462 createEntry(hash, key, value, i); 463 } 464 465 private void putAllForCreate(Map<? extends K, ? extends V> m) { 466 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) 467 putForCreate(e.getKey(), e.getValue()); 468 } 469 470 /** 471 * Rehashes the contents of this map into a new array with a 472 * larger capacity. This method is called automatically when the 473 * number of keys in this map reaches its threshold. 474 * 475 * If current capacity is MAXIMUM_CAPACITY, this method does not 476 * resize the map, but sets threshold to Integer.MAX_VALUE. 477 * This has the effect of preventing future calls. 478 * 479 * @param newCapacity the new capacity, MUST be a power of two; 480 * must be greater than current capacity unless current 481 * capacity is MAXIMUM_CAPACITY (in which case value 482 * is irrelevant). 483 */ 484 void resize(int newCapacity) { 485 Entry<?,?>[] oldTable = table; 486 int oldCapacity = oldTable.length; 487 if (oldCapacity == MAXIMUM_CAPACITY) { 488 threshold = Integer.MAX_VALUE; 489 return; 490 } 491 492 Entry<?,?>[] newTable = new Entry<?,?>[newCapacity]; 493 transfer(newTable); 494 table = newTable; 495 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); 496 } 497 498 /** 499 * Transfers all entries from current table to newTable. 500 */ 501 @SuppressWarnings("unchecked") 502 void transfer(Entry<?,?>[] newTable) { 503 Entry<?,?>[] src = table; 504 int newCapacity = newTable.length; 505 for (int j = 0; j < src.length; j++ ) { 506 Entry<K,V> e = (Entry<K,V>) src[j]; 507 while(null != e) { 508 Entry<K,V> next = e.next; 509 int i = indexFor(e.hash, newCapacity); 510 e.next = (Entry<K,V>) newTable[i]; 511 newTable[i] = e; 512 e = next; 513 } 514 } 515 Arrays.fill(table, null); 516 } 517 518 /** 519 * Copies all of the mappings from the specified map to this map. 520 * These mappings will replace any mappings that this map had for 521 * any of the keys currently in the specified map. 522 * 523 * @param m mappings to be stored in this map 524 * @throws NullPointerException if the specified map is null 525 */ 526 public void putAll(Map<? extends K, ? extends V> m) { 527 int numKeysToBeAdded = m.size(); 528 if (numKeysToBeAdded == 0) 529 return; 530 531 /* 532 * Expand the map if the map if the number of mappings to be added 533 * is greater than or equal to threshold. This is conservative; the 534 * obvious condition is (m.size() + size) >= threshold, but this 535 * condition could result in a map with twice the appropriate capacity, 536 * if the keys to be added overlap with the keys already in this map. 537 * By using the conservative calculation, we subject ourself 538 * to at most one extra resize. 539 */ 540 if (numKeysToBeAdded > threshold) { 541 int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1); 542 if (targetCapacity > MAXIMUM_CAPACITY) 543 targetCapacity = MAXIMUM_CAPACITY; 544 int newCapacity = table.length; 545 while (newCapacity < targetCapacity) 546 newCapacity <<= 1; 547 if (newCapacity > table.length) 548 resize(newCapacity); 549 } 550 551 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) 552 put(e.getKey(), e.getValue()); 553 } 554 555 /** 556 * Removes the mapping for the specified key from this map if present. 557 * 558 * @param key key whose mapping is to be removed from the map 559 * @return the previous value associated with <tt>key</tt>, or 560 * <tt>null</tt> if there was no mapping for <tt>key</tt>. 561 * (A <tt>null</tt> return can also indicate that the map 562 * previously associated <tt>null</tt> with <tt>key</tt>.) 563 */ 564 public V remove(Object key) { 565 Entry<K,V> e = removeEntryForKey(key); 566 return (e == null ? null : e.value); 567 } 568 569 /** 570 * Removes and returns the entry associated with the specified key 571 * in the HashMap. Returns null if the HashMap contains no mapping 572 * for this key. 573 */ 574 final Entry<K,V> removeEntryForKey(Object key) { 575 int hash = (key == null) ? 0 : hash(key); 576 int i = indexFor(hash, table.length); 577 @SuppressWarnings("unchecked") 578 Entry<K,V> prev = (Entry<K,V>)table[i]; 579 Entry<K,V> e = prev; 580 581 while (e != null) { 582 Entry<K,V> next = e.next; 583 Object k; 584 if (e.hash == hash && 585 ((k = e.key) == key || (key != null && key.equals(k)))) { 586 modCount++; 587 size--; 588 if (prev == e) 589 table[i] = next; 590 else 591 prev.next = next; 592 e.recordRemoval(this); 593 return e; 594 } 595 prev = e; 596 e = next; 597 } 598 599 return e; 600 } 601 602 /** 603 * Special version of remove for EntrySet using {@code Map.Entry.equals()} 604 * for matching. 605 */ 606 final Entry<K,V> removeMapping(Object o) { 607 if (!(o instanceof Map.Entry)) 608 return null; 609 610 Map.Entry<?,?> entry = (Map.Entry<?,?>) o; 611 Object key = entry.getKey(); 612 int hash = (key == null) ? 0 : hash(key.hashCode()); 613 int i = indexFor(hash, table.length); 614 @SuppressWarnings("unchecked") 615 Entry<K,V> prev = (Entry<K,V>)table[i]; 616 Entry<K,V> e = prev; 617 618 while (e != null) { 619 Entry<K,V> next = e.next; 620 if (e.hash == hash && e.equals(entry)) { 621 modCount++; 622 size--; 623 if (prev == e) 624 table[i] = next; 625 else 626 prev.next = next; 627 e.recordRemoval(this); 628 return e; 629 } 630 prev = e; 631 e = next; 632 } 633 634 return e; 635 } 636 637 /** 638 * Removes all of the mappings from this map. 639 * The map will be empty after this call returns. 640 */ 641 public void clear() { 642 modCount++; 643 Entry<?,?>[] tab = table; 644 for (int i = 0; i < tab.length; i++) 645 tab[i] = null; 646 size = 0; 647 } 648 649 /** 650 * Returns <tt>true</tt> if this map maps one or more keys to the 651 * specified value. 652 * 653 * @param value value whose presence in this map is to be tested 654 * @return <tt>true</tt> if this map maps one or more keys to the 655 * specified value 656 */ 657 public boolean containsValue(Object value) { 658 if (value == null) 659 return containsNullValue(); 660 661 Entry<?,?>[] tab = table; 662 for (int i = 0; i < tab.length ; i++) 663 for (Entry<?,?> e = tab[i] ; e != null ; e = e.next) 664 if (value.equals(e.value)) 665 return true; 666 return false; 667 } 668 669 /** 670 * Special-case code for containsValue with null argument 671 */ 672 private boolean containsNullValue() { 673 Entry<?,?>[] tab = table; 674 for (int i = 0; i < tab.length ; i++) 675 for (Entry<?,?> e = tab[i] ; e != null ; e = e.next) 676 if (e.value == null) 677 return true; 678 return false; 679 } 680 681 /** 682 * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and 683 * values themselves are not cloned. 684 * 685 * @return a shallow copy of this map 686 */ 687 @SuppressWarnings("unchecked") 688 public Object clone() { 689 HashMap<K,V> result = null; 690 try { 691 result = (HashMap<K,V>)super.clone(); 692 } catch (CloneNotSupportedException e) { 693 // assert false; 694 } 695 result.table = new Entry<?,?>[table.length]; 696 result.entrySet = null; 697 result.modCount = 0; 698 result.size = 0; 699 result.init(); 700 result.putAllForCreate(this); 701 702 return result; 703 } 704 705 static class Entry<K,V> implements Map.Entry<K,V> { 706 final K key; 707 V value; 708 Entry<K,V> next; 709 final int hash; 710 711 /** 712 * Creates new entry. 713 */ 714 Entry(int h, K k, V v, Entry<K,V> n) { 715 value = v; 716 next = n; 717 key = k; 718 hash = h; 719 } 720 721 public final K getKey() { 722 return key; 723 } 724 725 public final V getValue() { 726 return value; 727 } 728 729 public final V setValue(V newValue) { 730 V oldValue = value; 731 value = newValue; 732 return oldValue; 733 } 734 735 public final boolean equals(Object o) { 736 if (!(o instanceof Map.Entry)) 737 return false; 738 Map.Entry<?,?> e = (Map.Entry<?,?>)o; 739 Object k1 = getKey(); 740 Object k2 = e.getKey(); 741 if (k1 == k2 || (k1 != null && k1.equals(k2))) { 742 Object v1 = getValue(); 743 Object v2 = e.getValue(); 744 if (v1 == v2 || (v1 != null && v1.equals(v2))) 745 return true; 746 } 747 return false; 748 } 749 750 public final int hashCode() { 751 return (key==null ? 0 : key.hashCode()) ^ 752 (value==null ? 0 : value.hashCode()); 753 } 754 755 public final String toString() { 756 return getKey() + "=" + getValue(); 757 } 758 759 /** 760 * This method is invoked whenever the value in an entry is 761 * overwritten by an invocation of put(k,v) for a key k that's already 762 * in the HashMap. 763 */ 764 void recordAccess(HashMap<K,V> m) { 765 } 766 767 /** 768 * This method is invoked whenever the entry is 769 * removed from the table. 770 */ 771 void recordRemoval(HashMap<K,V> m) { 772 } 773 } 774 775 /** 776 * Adds a new entry with the specified key, value and hash code to 777 * the specified bucket. It is the responsibility of this 778 * method to resize the table if appropriate. 779 * 780 * Subclass overrides this to alter the behavior of put method. 781 */ 782 void addEntry(int hash, K key, V value, int bucketIndex) { 783 if ((size >= threshold) && (null != table[bucketIndex])) { 784 resize(2 * table.length); 785 hash = (null != key) ? hash(key) : 0; 786 bucketIndex = indexFor(hash, table.length); 787 } 788 789 createEntry(hash, key, value, bucketIndex); 790 } 791 792 /** 793 * Like addEntry except that this version is used when creating entries 794 * as part of Map construction or "pseudo-construction" (cloning, 795 * deserialization). This version needn't worry about resizing the table. 796 * 797 * Subclass overrides this to alter the behavior of HashMap(Map), 798 * clone, and readObject. 799 */ 800 void createEntry(int hash, K key, V value, int bucketIndex) { 801 @SuppressWarnings("unchecked") 802 Entry<K,V> e = (Entry<K,V>)table[bucketIndex]; 803 table[bucketIndex] = new Entry<>(hash, key, value, e); 804 size++; 805 } 806 807 private abstract class HashIterator<E> implements Iterator<E> { 808 Entry<?,?> next; // next entry to return 809 int expectedModCount; // For fast-fail 810 int index; // current slot 811 Entry<?,?> current; // current entry 812 813 HashIterator() { 814 expectedModCount = modCount; 815 if (size > 0) { // advance to first entry 816 Entry<?,?>[] t = table; 817 while (index < t.length && (next = t[index++]) == null) 818 ; 819 } 820 } 821 822 public final boolean hasNext() { 823 return next != null; 824 } 825 826 @SuppressWarnings("unchecked") 827 final Entry<K,V> nextEntry() { 828 if (modCount != expectedModCount) 829 throw new ConcurrentModificationException(); 830 Entry<?,?> e = next; 831 if (e == null) 832 throw new NoSuchElementException(); 833 834 if ((next = e.next) == null) { 835 Entry<?,?>[] t = table; 836 while (index < t.length && (next = t[index++]) == null) 837 ; 838 } 839 current = e; 840 return (Entry<K,V>)e; 841 } 842 843 public void remove() { 844 if (current == null) 845 throw new IllegalStateException(); 846 if (modCount != expectedModCount) 847 throw new ConcurrentModificationException(); 848 Object k = current.key; 849 current = null; 850 HashMap.this.removeEntryForKey(k); 851 expectedModCount = modCount; 852 } 853 } 854 855 private final class ValueIterator extends HashIterator<V> { 856 public V next() { 857 return nextEntry().value; 858 } 859 } 860 861 private final class KeyIterator extends HashIterator<K> { 862 public K next() { 863 return nextEntry().getKey(); 864 } 865 } 866 867 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> { 868 public Map.Entry<K,V> next() { 869 return nextEntry(); 870 } 871 } 872 873 // Subclass overrides these to alter behavior of views' iterator() method 874 Iterator<K> newKeyIterator() { 875 return new KeyIterator(); 876 } 877 Iterator<V> newValueIterator() { 878 return new ValueIterator(); 879 } 880 Iterator<Map.Entry<K,V>> newEntryIterator() { 881 return new EntryIterator(); 882 } 883 884 885 // Views 886 887 private transient Set<Map.Entry<K,V>> entrySet = null; 888 889 /** 890 * Returns a {@link Set} view of the keys contained in this map. 891 * The set is backed by the map, so changes to the map are 892 * reflected in the set, and vice-versa. If the map is modified 893 * while an iteration over the set is in progress (except through 894 * the iterator's own <tt>remove</tt> operation), the results of 895 * the iteration are undefined. The set supports element removal, 896 * which removes the corresponding mapping from the map, via the 897 * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, 898 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> 899 * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> 900 * operations. 901 */ 902 public Set<K> keySet() { 903 Set<K> ks = keySet; 904 return (ks != null ? ks : (keySet = new KeySet())); 905 } 906 907 private final class KeySet extends AbstractSet<K> { 908 public Iterator<K> iterator() { 909 return newKeyIterator(); 910 } 911 public int size() { 912 return size; 913 } 914 public boolean contains(Object o) { 915 return containsKey(o); 916 } 917 public boolean remove(Object o) { 918 return HashMap.this.removeEntryForKey(o) != null; 919 } 920 public void clear() { 921 HashMap.this.clear(); 922 } 923 } 924 925 /** 926 * Returns a {@link Collection} view of the values contained in this map. 927 * The collection is backed by the map, so changes to the map are 928 * reflected in the collection, and vice-versa. If the map is 929 * modified while an iteration over the collection is in progress 930 * (except through the iterator's own <tt>remove</tt> operation), 931 * the results of the iteration are undefined. The collection 932 * supports element removal, which removes the corresponding 933 * mapping from the map, via the <tt>Iterator.remove</tt>, 934 * <tt>Collection.remove</tt>, <tt>removeAll</tt>, 935 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not 936 * support the <tt>add</tt> or <tt>addAll</tt> operations. 937 */ 938 public Collection<V> values() { 939 Collection<V> vs = values; 940 return (vs != null ? vs : (values = new Values())); 941 } 942 943 private final class Values extends AbstractCollection<V> { 944 public Iterator<V> iterator() { 945 return newValueIterator(); 946 } 947 public int size() { 948 return size; 949 } 950 public boolean contains(Object o) { 951 return containsValue(o); 952 } 953 public void clear() { 954 HashMap.this.clear(); 955 } 956 } 957 958 /** 959 * Returns a {@link Set} view of the mappings contained in this map. 960 * The set is backed by the map, so changes to the map are 961 * reflected in the set, and vice-versa. If the map is modified 962 * while an iteration over the set is in progress (except through 963 * the iterator's own <tt>remove</tt> operation, or through the 964 * <tt>setValue</tt> operation on a map entry returned by the 965 * iterator) the results of the iteration are undefined. The set 966 * supports element removal, which removes the corresponding 967 * mapping from the map, via the <tt>Iterator.remove</tt>, 968 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and 969 * <tt>clear</tt> operations. It does not support the 970 * <tt>add</tt> or <tt>addAll</tt> operations. 971 * 972 * @return a set view of the mappings contained in this map 973 */ 974 public Set<Map.Entry<K,V>> entrySet() { 975 return entrySet0(); 976 } 977 978 private Set<Map.Entry<K,V>> entrySet0() { 979 Set<Map.Entry<K,V>> es = entrySet; 980 return es != null ? es : (entrySet = new EntrySet()); 981 } 982 983 private final class EntrySet extends AbstractSet<Map.Entry<K,V>> { 984 public Iterator<Map.Entry<K,V>> iterator() { 985 return newEntryIterator(); 986 } 987 public boolean contains(Object o) { 988 if (!(o instanceof Map.Entry)) 989 return false; 990 Map.Entry<?,?> e = (Map.Entry<?,?>) o; 991 Entry<K,V> candidate = getEntry(e.getKey()); 992 return candidate != null && candidate.equals(e); 993 } 994 public boolean remove(Object o) { 995 return removeMapping(o) != null; 996 } 997 public int size() { 998 return size; 999 } 1000 public void clear() { 1001 HashMap.this.clear(); 1002 } 1003 } 1004 1005 /** 1006 * Save the state of the <tt>HashMap</tt> instance to a stream (i.e., 1007 * serialize it). 1008 * 1009 * @serialData The <i>capacity</i> of the HashMap (the length of the 1010 * bucket array) is emitted (int), followed by the 1011 * <i>size</i> (an int, the number of key-value 1012 * mappings), followed by the key (Object) and value (Object) 1013 * for each key-value mapping. The key-value mappings are 1014 * emitted in no particular order. 1015 */ 1016 private void writeObject(java.io.ObjectOutputStream s) 1017 throws IOException 1018 { 1019 Iterator<Map.Entry<K,V>> i = 1020 (size > 0) ? entrySet0().iterator() : null; 1021 1022 // Write out the threshold, loadfactor, and any hidden stuff 1023 s.defaultWriteObject(); 1024 1025 // Write out number of buckets 1026 s.writeInt(table.length); 1027 1028 // Write out size (number of Mappings) 1029 s.writeInt(size); 1030 1031 // Write out keys and values (alternating) 1032 if (size > 0) { 1033 for(Map.Entry<K,V> e : entrySet0()) { 1034 s.writeObject(e.getKey()); 1035 s.writeObject(e.getValue()); 1036 } 1037 } 1038 } 1039 1040 private static final long serialVersionUID = 362498820763181265L; 1041 1042 /** 1043 * Reconstitute the {@code HashMap} instance from a stream (i.e., 1044 * deserialize it). 1045 */ 1046 private void readObject(java.io.ObjectInputStream s) 1047 throws IOException, ClassNotFoundException 1048 { 1049 // Read in the threshold (ignored), loadfactor, and any hidden stuff 1050 s.defaultReadObject(); 1051 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 1052 throw new InvalidObjectException("Illegal load factor: " + 1053 loadFactor); 1054 1055 // set hashMask 1056 Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET, 1057 sun.misc.Hashing.randomHashSeed(this)); 1058 1059 // Read in number of buckets and allocate the bucket array; 1060 s.readInt(); // ignored 1061 1062 // Read number of mappings 1063 int mappings = s.readInt(); 1064 if (mappings < 0) 1065 throw new InvalidObjectException("Illegal mappings count: " + 1066 mappings); 1067 1068 int initialCapacity = (int) Math.min( 1069 // capacity chosen by number of mappings 1070 // and desired load (if >= 0.25) 1071 mappings * Math.min(1 / loadFactor, 4.0f), 1072 // we have limits... 1073 HashMap.MAXIMUM_CAPACITY); 1074 int capacity = 1; 1075 // find smallest power of two which holds all mappings 1076 while (capacity < initialCapacity) { 1077 capacity <<= 1; 1078 } 1079 1080 table = new Entry[capacity]; 1081 threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); 1082 init(); // Give subclass a chance to do its thing. 1083 1084 1085 // Read the keys and values, and put the mappings in the HashMap 1086 for (int i=0; i<mappings; i++) { 1087 @SuppressWarnings("unchecked") 1088 K key = (K) s.readObject(); 1089 @SuppressWarnings("unchecked") 1090 V value = (V) s.readObject(); 1091 putForCreate(key, value); 1092 } 1093 } 1094 1095 // These methods are used when serializing HashSets 1096 int capacity() { return table.length; } 1097 float loadFactor() { return loadFactor; } 1098 }