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