1 /* 2 * Copyright (c) 1994, 2011, 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 * This class implements a hash table, which maps keys to values. Any 31 * non-<code>null</code> object can be used as a key or as a value. <p> 32 * 33 * To successfully store and retrieve objects from a hashtable, the 34 * objects used as keys must implement the <code>hashCode</code> 35 * method and the <code>equals</code> method. <p> 36 * 37 * An instance of <code>Hashtable</code> has two parameters that affect its 38 * performance: <i>initial capacity</i> and <i>load factor</i>. The 39 * <i>capacity</i> is the number of <i>buckets</i> in the hash table, and the 40 * <i>initial capacity</i> is simply the capacity at the time the hash table 41 * is created. Note that the hash table is <i>open</i>: in the case of a "hash 42 * collision", a single bucket stores multiple entries, which must be searched 43 * sequentially. The <i>load factor</i> is a measure of how full the hash 44 * table is allowed to get before its capacity is automatically increased. 45 * The initial capacity and load factor parameters are merely hints to 46 * the implementation. The exact details as to when and whether the rehash 47 * method is invoked are implementation-dependent.<p> 48 * 49 * Generally, the default load factor (.75) offers a good tradeoff between 50 * time and space costs. Higher values decrease the space overhead but 51 * increase the time cost to look up an entry (which is reflected in most 52 * <tt>Hashtable</tt> operations, including <tt>get</tt> and <tt>put</tt>).<p> 53 * 54 * The initial capacity controls a tradeoff between wasted space and the 55 * need for <code>rehash</code> operations, which are time-consuming. 56 * No <code>rehash</code> operations will <i>ever</i> occur if the initial 57 * capacity is greater than the maximum number of entries the 58 * <tt>Hashtable</tt> will contain divided by its load factor. However, 59 * setting the initial capacity too high can waste space.<p> 60 * 61 * If many entries are to be made into a <code>Hashtable</code>, 62 * creating it with a sufficiently large capacity may allow the 63 * entries to be inserted more efficiently than letting it perform 64 * automatic rehashing as needed to grow the table. <p> 65 * 66 * This example creates a hashtable of numbers. It uses the names of 67 * the numbers as keys: 68 * <pre> {@code 69 * Hashtable<String, Integer> numbers 70 * = new Hashtable<String, Integer>(); 71 * numbers.put("one", 1); 72 * numbers.put("two", 2); 73 * numbers.put("three", 3);}</pre> 74 * 75 * <p>To retrieve a number, use the following code: 76 * <pre> {@code 77 * Integer n = numbers.get("two"); 78 * if (n != null) { 79 * System.out.println("two = " + n); 80 * }}</pre> 81 * 82 * <p>The iterators returned by the <tt>iterator</tt> method of the collections 83 * returned by all of this class's "collection view methods" are 84 * <em>fail-fast</em>: if the Hashtable is structurally modified at any time 85 * after the iterator is created, in any way except through the iterator's own 86 * <tt>remove</tt> method, the iterator will throw a {@link 87 * ConcurrentModificationException}. Thus, in the face of concurrent 88 * modification, the iterator fails quickly and cleanly, rather than risking 89 * arbitrary, non-deterministic behavior at an undetermined time in the future. 90 * The Enumerations returned by Hashtable's keys and elements methods are 91 * <em>not</em> fail-fast. 92 * 93 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed 94 * as it is, generally speaking, impossible to make any hard guarantees in the 95 * presence of unsynchronized concurrent modification. Fail-fast iterators 96 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. 97 * Therefore, it would be wrong to write a program that depended on this 98 * exception for its correctness: <i>the fail-fast behavior of iterators 99 * should be used only to detect bugs.</i> 100 * 101 * <p>As of the Java 2 platform v1.2, this class was retrofitted to 102 * implement the {@link Map} interface, making it a member of the 103 * <a href="{@docRoot}/../technotes/guides/collections/index.html"> 104 * 105 * Java Collections Framework</a>. Unlike the new collection 106 * implementations, {@code Hashtable} is synchronized. If a 107 * thread-safe implementation is not needed, it is recommended to use 108 * {@link HashMap} in place of {@code Hashtable}. If a thread-safe 109 * highly-concurrent implementation is desired, then it is recommended 110 * to use {@link java.util.concurrent.ConcurrentHashMap} in place of 111 * {@code Hashtable}. 112 * 113 * @author Arthur van Hoff 114 * @author Josh Bloch 115 * @author Neal Gafter 116 * @see Object#equals(java.lang.Object) 117 * @see Object#hashCode() 118 * @see Hashtable#rehash() 119 * @see Collection 120 * @see Map 121 * @see HashMap 122 * @see TreeMap 123 * @since JDK1.0 124 */ 125 public class Hashtable<K,V> 126 extends Dictionary<K,V> 127 implements Map<K,V>, Cloneable, java.io.Serializable { 128 129 /** 130 * The hash table data. 131 */ 132 private transient Entry<?,?>[] table; 133 134 /** 135 * The total number of entries in the hash table. 136 */ 137 private transient int count; 138 139 /** 140 * The table is rehashed when its size exceeds this threshold. (The 141 * value of this field is (int)(capacity * loadFactor).) 142 * 143 * @serial 144 */ 145 private int threshold; 146 147 /** 148 * The load factor for the hashtable. 149 * 150 * @serial 151 */ 152 private float loadFactor; 153 154 /** 155 * The number of times this Hashtable has been structurally modified 156 * Structural modifications are those that change the number of entries in 157 * the Hashtable or otherwise modify its internal structure (e.g., 158 * rehash). This field is used to make iterators on Collection-views of 159 * the Hashtable fail-fast. (See ConcurrentModificationException). 160 */ 161 private transient int modCount = 0; 162 163 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 164 private static final long serialVersionUID = 1421746759512286392L; 165 166 /** 167 * Constructs a new, empty hashtable with the specified initial 168 * capacity and the specified load factor. 169 * 170 * @param initialCapacity the initial capacity of the hashtable. 171 * @param loadFactor the load factor of the hashtable. 172 * @exception IllegalArgumentException if the initial capacity is less 173 * than zero, or if the load factor is nonpositive. 174 */ 175 public Hashtable(int initialCapacity, float loadFactor) { 176 if (initialCapacity < 0) 177 throw new IllegalArgumentException("Illegal Capacity: "+ 178 initialCapacity); 179 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 180 throw new IllegalArgumentException("Illegal Load: "+loadFactor); 181 182 if (initialCapacity==0) 183 initialCapacity = 1; 184 this.loadFactor = loadFactor; 185 table = new Entry[initialCapacity]; 186 threshold = (int)(initialCapacity * loadFactor); 187 } 188 189 /** 190 * Constructs a new, empty hashtable with the specified initial capacity 191 * and default load factor (0.75). 192 * 193 * @param initialCapacity the initial capacity of the hashtable. 194 * @exception IllegalArgumentException if the initial capacity is less 195 * than zero. 196 */ 197 public Hashtable(int initialCapacity) { 198 this(initialCapacity, 0.75f); 199 } 200 201 /** 202 * Constructs a new, empty hashtable with a default initial capacity (11) 203 * and load factor (0.75). 204 */ 205 public Hashtable() { 206 this(11, 0.75f); 207 } 208 209 /** 210 * Constructs a new hashtable with the same mappings as the given 211 * Map. The hashtable is created with an initial capacity sufficient to 212 * hold the mappings in the given Map and a default load factor (0.75). 213 * 214 * @param t the map whose mappings are to be placed in this map. 215 * @throws NullPointerException if the specified map is null. 216 * @since 1.2 217 */ 218 public Hashtable(Map<? extends K, ? extends V> t) { 219 this(Math.max(2*t.size(), 11), 0.75f); 220 putAll(t); 221 } 222 223 /** 224 * Returns the number of keys in this hashtable. 225 * 226 * @return the number of keys in this hashtable. 227 */ 228 public synchronized int size() { 229 return count; 230 } 231 232 /** 233 * Tests if this hashtable maps no keys to values. 234 * 235 * @return <code>true</code> if this hashtable maps no keys to values; 236 * <code>false</code> otherwise. 237 */ 238 public synchronized boolean isEmpty() { 239 return count == 0; 240 } 241 242 /** 243 * Returns an enumeration of the keys in this hashtable. 244 * 245 * @return an enumeration of the keys in this hashtable. 246 * @see Enumeration 247 * @see #elements() 248 * @see #keySet() 249 * @see Map 250 */ 251 public synchronized Enumeration<K> keys() { 252 return this.<K>getEnumeration(KEYS); 253 } 254 255 /** 256 * Returns an enumeration of the values in this hashtable. 257 * Use the Enumeration methods on the returned object to fetch the elements 258 * sequentially. 259 * 260 * @return an enumeration of the values in this hashtable. 261 * @see java.util.Enumeration 262 * @see #keys() 263 * @see #values() 264 * @see Map 265 */ 266 public synchronized Enumeration<V> elements() { 267 return this.<V>getEnumeration(VALUES); 268 } 269 270 /** 271 * Tests if some key maps into the specified value in this hashtable. 272 * This operation is more expensive than the {@link #containsKey 273 * containsKey} method. 274 * 275 * <p>Note that this method is identical in functionality to 276 * {@link #containsValue containsValue}, (which is part of the 277 * {@link Map} interface in the collections framework). 278 * 279 * @param value a value to search for 280 * @return <code>true</code> if and only if some key maps to the 281 * <code>value</code> argument in this hashtable as 282 * determined by the <tt>equals</tt> method; 283 * <code>false</code> otherwise. 284 * @exception NullPointerException if the value is <code>null</code> 285 */ 286 public synchronized boolean contains(Object value) { 287 if (value == null) { 288 throw new NullPointerException(); 289 } 290 291 Entry<?,?> tab[] = table; 292 for (int i = tab.length ; i-- > 0 ;) { 293 for (Entry<?,?> e = tab[i] ; e != null ; e = e.next) { 294 if (e.value.equals(value)) { 295 return true; 296 } 297 } 298 } 299 return false; 300 } 301 302 /** 303 * Returns true if this hashtable maps one or more keys to this value. 304 * 305 * <p>Note that this method is identical in functionality to {@link 306 * #contains contains} (which predates the {@link Map} interface). 307 * 308 * @param value value whose presence in this hashtable is to be tested 309 * @return <tt>true</tt> if this map maps one or more keys to the 310 * specified value 311 * @throws NullPointerException if the value is <code>null</code> 312 * @since 1.2 313 */ 314 public boolean containsValue(Object value) { 315 return contains(value); 316 } 317 318 /** 319 * Tests if the specified object is a key in this hashtable. 320 * 321 * @param key possible key 322 * @return <code>true</code> if and only if the specified object 323 * is a key in this hashtable, as determined by the 324 * <tt>equals</tt> method; <code>false</code> otherwise. 325 * @throws NullPointerException if the key is <code>null</code> 326 * @see #contains(Object) 327 */ 328 public synchronized boolean containsKey(Object key) { 329 Entry<?,?> tab[] = table; 330 int hash = key.hashCode(); 331 int index = (hash & 0x7FFFFFFF) % tab.length; 332 for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { 333 if ((e.hash == hash) && e.key.equals(key)) { 334 return true; 335 } 336 } 337 return false; 338 } 339 340 /** 341 * Returns the value to which the specified key is mapped, 342 * or {@code null} if this map contains no mapping for the key. 343 * 344 * <p>More formally, if this map contains a mapping from a key 345 * {@code k} to a value {@code v} such that {@code (key.equals(k))}, 346 * then this method returns {@code v}; otherwise it returns 347 * {@code null}. (There can be at most one such mapping.) 348 * 349 * @param key the key whose associated value is to be returned 350 * @return the value to which the specified key is mapped, or 351 * {@code null} if this map contains no mapping for the key 352 * @throws NullPointerException if the specified key is null 353 * @see #put(Object, Object) 354 */ 355 public synchronized V get(Object key) { 356 Entry<?,?> tab[] = table; 357 int hash = key.hashCode(); 358 int index = (hash & 0x7FFFFFFF) % tab.length; 359 for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { 360 if ((e.hash == hash) && e.key.equals(key)) { 361 return (V)e.value; 362 } 363 } 364 return null; 365 } 366 367 /** 368 * The maximum size of array to allocate. 369 * Some VMs reserve some header words in an array. 370 * Attempts to allocate larger arrays may result in 371 * OutOfMemoryError: Requested array size exceeds VM limit 372 */ 373 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; 374 375 /** 376 * Increases the capacity of and internally reorganizes this 377 * hashtable, in order to accommodate and access its entries more 378 * efficiently. This method is called automatically when the 379 * number of keys in the hashtable exceeds this hashtable's capacity 380 * and load factor. 381 */ 382 @SuppressWarnings("unchecked") 383 protected void rehash() { 384 int oldCapacity = table.length; 385 Entry<?,?>[] oldMap = table; 386 387 // overflow-conscious code 388 int newCapacity = (oldCapacity << 1) + 1; 389 if (newCapacity - MAX_ARRAY_SIZE > 0) { 390 if (oldCapacity == MAX_ARRAY_SIZE) 391 // Keep running with MAX_ARRAY_SIZE buckets 392 return; 393 newCapacity = MAX_ARRAY_SIZE; 394 } 395 Entry<?,?>[] newMap = new Entry<?,?>[newCapacity]; 396 397 modCount++; 398 threshold = (int)(newCapacity * loadFactor); 399 table = newMap; 400 401 for (int i = oldCapacity ; i-- > 0 ;) { 402 for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) { 403 Entry<K,V> e = old; 404 old = old.next; 405 406 int index = (e.hash & 0x7FFFFFFF) % newCapacity; 407 e.next = (Entry<K,V>)newMap[index]; 408 newMap[index] = e; 409 } 410 } 411 } 412 413 /** 414 * Maps the specified <code>key</code> to the specified 415 * <code>value</code> in this hashtable. Neither the key nor the 416 * value can be <code>null</code>. <p> 417 * 418 * The value can be retrieved by calling the <code>get</code> method 419 * with a key that is equal to the original key. 420 * 421 * @param key the hashtable key 422 * @param value the value 423 * @return the previous value of the specified key in this hashtable, 424 * or <code>null</code> if it did not have one 425 * @exception NullPointerException if the key or value is 426 * <code>null</code> 427 * @see Object#equals(Object) 428 * @see #get(Object) 429 */ 430 public synchronized V put(K key, V value) { 431 // Make sure the value is not null 432 if (value == null) { 433 throw new NullPointerException(); 434 } 435 436 // Makes sure the key is not already in the hashtable. 437 Entry<?,?> tab[] = table; 438 int hash = key.hashCode(); 439 int index = (hash & 0x7FFFFFFF) % tab.length; 440 for (@SuppressWarnings("unchecked") 441 Entry<K,V> e = (Entry<K,V>)tab[index] ; e != null ; e = e.next) { 442 if ((e.hash == hash) && e.key.equals(key)) { 443 V old = e.value; 444 e.value = value; 445 return old; 446 } 447 } 448 449 modCount++; 450 if (count >= threshold) { 451 // Rehash the table if the threshold is exceeded 452 rehash(); 453 454 tab = table; 455 index = (hash & 0x7FFFFFFF) % tab.length; 456 } 457 458 // Creates the new entry. 459 @SuppressWarnings("unchecked") 460 Entry<K,V> e = (Entry<K,V>)tab[index]; 461 tab[index] = new Entry<>(hash, key, value, e); 462 count++; 463 return null; 464 } 465 466 /** 467 * Removes the key (and its corresponding value) from this 468 * hashtable. This method does nothing if the key is not in the hashtable. 469 * 470 * @param key the key that needs to be removed 471 * @return the value to which the key had been mapped in this hashtable, 472 * or <code>null</code> if the key did not have a mapping 473 * @throws NullPointerException if the key is <code>null</code> 474 */ 475 public synchronized V remove(Object key) { 476 Entry<?,?> tab[] = table; 477 int hash = key.hashCode(); 478 int index = (hash & 0x7FFFFFFF) % tab.length; 479 for (@SuppressWarnings("unchecked") 480 Entry<K,V> e = (Entry<K,V>)tab[index], prev = null ; e != null ; prev = e, e = e.next) { 481 if ((e.hash == hash) && e.key.equals(key)) { 482 modCount++; 483 if (prev != null) { 484 prev.next = e.next; 485 } else { 486 tab[index] = e.next; 487 } 488 count--; 489 V oldValue = e.value; 490 e.value = null; 491 return oldValue; 492 } 493 } 494 return null; 495 } 496 497 /** 498 * Copies all of the mappings from the specified map to this hashtable. 499 * These mappings will replace any mappings that this hashtable had for any 500 * of the keys currently in the specified map. 501 * 502 * @param t mappings to be stored in this map 503 * @throws NullPointerException if the specified map is null 504 * @since 1.2 505 */ 506 public synchronized void putAll(Map<? extends K, ? extends V> t) { 507 for (Map.Entry<? extends K, ? extends V> e : t.entrySet()) 508 put(e.getKey(), e.getValue()); 509 } 510 511 /** 512 * Clears this hashtable so that it contains no keys. 513 */ 514 public synchronized void clear() { 515 Entry<?,?> tab[] = table; 516 modCount++; 517 for (int index = tab.length; --index >= 0; ) 518 tab[index] = null; 519 count = 0; 520 } 521 522 /** 523 * Creates a shallow copy of this hashtable. All the structure of the 524 * hashtable itself is copied, but the keys and values are not cloned. 525 * This is a relatively expensive operation. 526 * 527 * @return a clone of the hashtable 528 */ 529 public synchronized Object clone() { 530 try { 531 Hashtable<?,?> t = (Hashtable<?,?>)super.clone(); 532 t.table = new Entry<?,?>[table.length]; 533 for (int i = table.length ; i-- > 0 ; ) { 534 t.table[i] = (table[i] != null) 535 ? (Entry<?,?>) table[i].clone() : null; 536 } 537 t.keySet = null; 538 t.entrySet = null; 539 t.values = null; 540 t.modCount = 0; 541 return t; 542 } catch (CloneNotSupportedException e) { 543 // this shouldn't happen, since we are Cloneable 544 throw new InternalError(e); 545 } 546 } 547 548 /** 549 * Returns a string representation of this <tt>Hashtable</tt> object 550 * in the form of a set of entries, enclosed in braces and separated 551 * by the ASCII characters "<tt>, </tt>" (comma and space). Each 552 * entry is rendered as the key, an equals sign <tt>=</tt>, and the 553 * associated element, where the <tt>toString</tt> method is used to 554 * convert the key and element to strings. 555 * 556 * @return a string representation of this hashtable 557 */ 558 public synchronized String toString() { 559 int max = size() - 1; 560 if (max == -1) 561 return "{}"; 562 563 StringBuilder sb = new StringBuilder(); 564 Iterator<Map.Entry<K,V>> it = entrySet().iterator(); 565 566 sb.append('{'); 567 for (int i = 0; ; i++) { 568 Map.Entry<K,V> e = it.next(); 569 K key = e.getKey(); 570 V value = e.getValue(); 571 sb.append(key == this ? "(this Map)" : key.toString()); 572 sb.append('='); 573 sb.append(value == this ? "(this Map)" : value.toString()); 574 575 if (i == max) 576 return sb.append('}').toString(); 577 sb.append(", "); 578 } 579 } 580 581 582 private <T> Enumeration<T> getEnumeration(int type) { 583 if (count == 0) { 584 return Collections.emptyEnumeration(); 585 } else { 586 return new Enumerator<>(type, false); 587 } 588 } 589 590 private <T> Iterator<T> getIterator(int type) { 591 if (count == 0) { 592 return Collections.emptyIterator(); 593 } else { 594 return new Enumerator<>(type, true); 595 } 596 } 597 598 // Views 599 600 /** 601 * Each of these fields are initialized to contain an instance of the 602 * appropriate view the first time this view is requested. The views are 603 * stateless, so there's no reason to create more than one of each. 604 */ 605 private transient volatile Set<K> keySet = null; 606 private transient volatile Set<Map.Entry<K,V>> entrySet = null; 607 private transient volatile Collection<V> values = null; 608 609 /** 610 * Returns a {@link Set} view of the keys contained in this map. 611 * The set is backed by the map, so changes to the map are 612 * reflected in the set, and vice-versa. If the map is modified 613 * while an iteration over the set is in progress (except through 614 * the iterator's own <tt>remove</tt> operation), the results of 615 * the iteration are undefined. The set supports element removal, 616 * which removes the corresponding mapping from the map, via the 617 * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, 618 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> 619 * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> 620 * operations. 621 * 622 * @since 1.2 623 */ 624 public Set<K> keySet() { 625 if (keySet == null) 626 keySet = Collections.synchronizedSet(new KeySet(), this); 627 return keySet; 628 } 629 630 private class KeySet extends AbstractSet<K> { 631 public Iterator<K> iterator() { 632 return getIterator(KEYS); 633 } 634 public int size() { 635 return count; 636 } 637 public boolean contains(Object o) { 638 return containsKey(o); 639 } 640 public boolean remove(Object o) { 641 return Hashtable.this.remove(o) != null; 642 } 643 public void clear() { 644 Hashtable.this.clear(); 645 } 646 } 647 648 /** 649 * Returns a {@link Set} view of the mappings contained in this map. 650 * The set is backed by the map, so changes to the map are 651 * reflected in the set, and vice-versa. If the map is modified 652 * while an iteration over the set is in progress (except through 653 * the iterator's own <tt>remove</tt> operation, or through the 654 * <tt>setValue</tt> operation on a map entry returned by the 655 * iterator) the results of the iteration are undefined. The set 656 * supports element removal, which removes the corresponding 657 * mapping from the map, via the <tt>Iterator.remove</tt>, 658 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and 659 * <tt>clear</tt> operations. It does not support the 660 * <tt>add</tt> or <tt>addAll</tt> operations. 661 * 662 * @since 1.2 663 */ 664 public Set<Map.Entry<K,V>> entrySet() { 665 if (entrySet==null) 666 entrySet = Collections.synchronizedSet(new EntrySet(), this); 667 return entrySet; 668 } 669 670 private class EntrySet extends AbstractSet<Map.Entry<K,V>> { 671 public Iterator<Map.Entry<K,V>> iterator() { 672 return getIterator(ENTRIES); 673 } 674 675 public boolean add(Map.Entry<K,V> o) { 676 return super.add(o); 677 } 678 679 public boolean contains(Object o) { 680 if (!(o instanceof Map.Entry)) 681 return false; 682 Map.Entry<?,?> entry = (Map.Entry<?,?>)o; 683 Object key = entry.getKey(); 684 Entry<?,?>[] tab = table; 685 int hash = key.hashCode(); 686 int index = (hash & 0x7FFFFFFF) % tab.length; 687 688 for (Entry<?,?> e = tab[index]; e != null; e = e.next) 689 if (e.hash==hash && e.equals(entry)) 690 return true; 691 return false; 692 } 693 694 public boolean remove(Object o) { 695 if (!(o instanceof Map.Entry)) 696 return false; 697 Map.Entry<?,?> entry = (Map.Entry<?,?>) o; 698 Object key = entry.getKey(); 699 Entry<?,?>[] tab = table; 700 int hash = key.hashCode(); 701 int index = (hash & 0x7FFFFFFF) % tab.length; 702 703 for (@SuppressWarnings("unchecked") 704 Entry<K,V> e = (Entry<K,V>)tab[index], prev = null; e != null; 705 prev = e, e = e.next) { 706 if (e.hash==hash && e.equals(entry)) { 707 modCount++; 708 if (prev != null) 709 prev.next = e.next; 710 else 711 tab[index] = e.next; 712 713 count--; 714 e.value = null; 715 return true; 716 } 717 } 718 return false; 719 } 720 721 public int size() { 722 return count; 723 } 724 725 public void clear() { 726 Hashtable.this.clear(); 727 } 728 } 729 730 /** 731 * Returns a {@link Collection} view of the values contained in this map. 732 * The collection is backed by the map, so changes to the map are 733 * reflected in the collection, and vice-versa. If the map is 734 * modified while an iteration over the collection is in progress 735 * (except through the iterator's own <tt>remove</tt> operation), 736 * the results of the iteration are undefined. The collection 737 * supports element removal, which removes the corresponding 738 * mapping from the map, via the <tt>Iterator.remove</tt>, 739 * <tt>Collection.remove</tt>, <tt>removeAll</tt>, 740 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not 741 * support the <tt>add</tt> or <tt>addAll</tt> operations. 742 * 743 * @since 1.2 744 */ 745 public Collection<V> values() { 746 if (values==null) 747 values = Collections.synchronizedCollection(new ValueCollection(), 748 this); 749 return values; 750 } 751 752 private class ValueCollection extends AbstractCollection<V> { 753 public Iterator<V> iterator() { 754 return getIterator(VALUES); 755 } 756 public int size() { 757 return count; 758 } 759 public boolean contains(Object o) { 760 return containsValue(o); 761 } 762 public void clear() { 763 Hashtable.this.clear(); 764 } 765 } 766 767 // Comparison and hashing 768 769 /** 770 * Compares the specified Object with this Map for equality, 771 * as per the definition in the Map interface. 772 * 773 * @param o object to be compared for equality with this hashtable 774 * @return true if the specified Object is equal to this Map 775 * @see Map#equals(Object) 776 * @since 1.2 777 */ 778 public synchronized boolean equals(Object o) { 779 if (o == this) 780 return true; 781 782 if (!(o instanceof Map)) 783 return false; 784 Map<?,?> t = (Map<?,?>) o; 785 if (t.size() != size()) 786 return false; 787 788 try { 789 Iterator<Map.Entry<K,V>> i = entrySet().iterator(); 790 while (i.hasNext()) { 791 Map.Entry<K,V> e = i.next(); 792 K key = e.getKey(); 793 V value = e.getValue(); 794 if (value == null) { 795 if (!(t.get(key)==null && t.containsKey(key))) 796 return false; 797 } else { 798 if (!value.equals(t.get(key))) 799 return false; 800 } 801 } 802 } catch (ClassCastException unused) { 803 return false; 804 } catch (NullPointerException unused) { 805 return false; 806 } 807 808 return true; 809 } 810 811 /** 812 * Returns the hash code value for this Map as per the definition in the 813 * Map interface. 814 * 815 * @see Map#hashCode() 816 * @since 1.2 817 */ 818 public synchronized int hashCode() { 819 /* 820 * This code detects the recursion caused by computing the hash code 821 * of a self-referential hash table and prevents the stack overflow 822 * that would otherwise result. This allows certain 1.1-era 823 * applets with self-referential hash tables to work. This code 824 * abuses the loadFactor field to do double-duty as a hashCode 825 * in progress flag, so as not to worsen the space performance. 826 * A negative load factor indicates that hash code computation is 827 * in progress. 828 */ 829 int h = 0; 830 if (count == 0 || loadFactor < 0) 831 return h; // Returns zero 832 833 loadFactor = -loadFactor; // Mark hashCode computation in progress 834 Entry<?,?>[] tab = table; 835 for (int i = 0; i < tab.length; i++) 836 for (Entry<?,?> e = tab[i]; e != null; e = e.next) 837 h += e.key.hashCode() ^ e.value.hashCode(); 838 loadFactor = -loadFactor; // Mark hashCode computation complete 839 840 return h; 841 } 842 843 /** 844 * Save the state of the Hashtable to a stream (i.e., serialize it). 845 * 846 * @serialData The <i>capacity</i> of the Hashtable (the length of the 847 * bucket array) is emitted (int), followed by the 848 * <i>size</i> of the Hashtable (the number of key-value 849 * mappings), followed by the key (Object) and value (Object) 850 * for each key-value mapping represented by the Hashtable 851 * The key-value mappings are emitted in no particular order. 852 */ 853 private void writeObject(java.io.ObjectOutputStream s) 854 throws IOException { 855 Entry<Object, Object> entryStack = null; 856 857 synchronized (this) { 858 // Write out the length, threshold, loadfactor 859 s.defaultWriteObject(); 860 861 // Write out length, count of elements 862 s.writeInt(table.length); 863 s.writeInt(count); 864 865 // Stack copies of the entries in the table 866 for (int index = 0; index < table.length; index++) { 867 Entry<?,?> entry = table[index]; 868 869 while (entry != null) { 870 entryStack = 871 new Entry<>(0, entry.key, entry.value, entryStack); 872 entry = entry.next; 873 } 874 } 875 } 876 877 // Write out the key/value objects from the stacked entries 878 while (entryStack != null) { 879 s.writeObject(entryStack.key); 880 s.writeObject(entryStack.value); 881 entryStack = entryStack.next; 882 } 883 } 884 885 /** 886 * Reconstitute the Hashtable from a stream (i.e., deserialize it). 887 */ 888 private void readObject(java.io.ObjectInputStream s) 889 throws IOException, ClassNotFoundException 890 { 891 // Read in the length, threshold, and loadfactor 892 s.defaultReadObject(); 893 894 // Read the original length of the array and number of elements 895 int origlength = s.readInt(); 896 int elements = s.readInt(); 897 898 // Compute new size with a bit of room 5% to grow but 899 // no larger than the original size. Make the length 900 // odd if it's large enough, this helps distribute the entries. 901 // Guard against the length ending up zero, that's not valid. 902 int length = (int)(elements * loadFactor) + (elements / 20) + 3; 903 if (length > elements && (length & 1) == 0) 904 length--; 905 if (origlength > 0 && length > origlength) 906 length = origlength; 907 908 Entry<?,?>[] table = new Entry[length]; 909 count = 0; 910 911 // Read the number of elements and then all the key/value objects 912 for (; elements > 0; elements--) { 913 @SuppressWarnings("unchecked") 914 K key = (K)s.readObject(); 915 @SuppressWarnings("unchecked") 916 V value = (V)s.readObject(); 917 // synch could be eliminated for performance 918 reconstitutionPut(table, key, value); 919 } 920 this.table = table; 921 } 922 923 /** 924 * The put method used by readObject. This is provided because put 925 * is overridable and should not be called in readObject since the 926 * subclass will not yet be initialized. 927 * 928 * <p>This differs from the regular put method in several ways. No 929 * checking for rehashing is necessary since the number of elements 930 * initially in the table is known. The modCount is not incremented 931 * because we are creating a new instance. Also, no return value 932 * is needed. 933 */ 934 private void reconstitutionPut(Entry<?,?>[] tab, K key, V value) 935 throws StreamCorruptedException 936 { 937 if (value == null) { 938 throw new java.io.StreamCorruptedException(); 939 } 940 // Makes sure the key is not already in the hashtable. 941 // This should not happen in deserialized version. 942 int hash = key.hashCode(); 943 int index = (hash & 0x7FFFFFFF) % tab.length; 944 for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { 945 if ((e.hash == hash) && e.key.equals(key)) { 946 throw new java.io.StreamCorruptedException(); 947 } 948 } 949 // Creates the new entry. 950 @SuppressWarnings("unchecked") 951 Entry<K,V> e = (Entry<K,V>)tab[index]; 952 tab[index] = new Entry<>(hash, key, value, e); 953 count++; 954 } 955 956 /** 957 * Hashtable collision list. 958 */ 959 private static class Entry<K,V> implements Map.Entry<K,V> { 960 int hash; 961 K key; 962 V value; 963 Entry<K,V> next; 964 965 protected Entry(int hash, K key, V value, Entry<K,V> next) { 966 this.hash = hash; 967 this.key = key; 968 this.value = value; 969 this.next = next; 970 } 971 972 @SuppressWarnings("unchecked") 973 protected Object clone() { 974 return new Entry<>(hash, key, value, 975 (next==null ? null : (Entry<K,V>) next.clone())); 976 } 977 978 // Map.Entry Ops 979 980 public K getKey() { 981 return key; 982 } 983 984 public V getValue() { 985 return value; 986 } 987 988 public V setValue(V value) { 989 if (value == null) 990 throw new NullPointerException(); 991 992 V oldValue = this.value; 993 this.value = value; 994 return oldValue; 995 } 996 997 public boolean equals(Object o) { 998 if (!(o instanceof Map.Entry)) 999 return false; 1000 Map.Entry<?,?> e = (Map.Entry<?,?>)o; 1001 1002 return (key==null ? e.getKey()==null : key.equals(e.getKey())) && 1003 (value==null ? e.getValue()==null : value.equals(e.getValue())); 1004 } 1005 1006 public int hashCode() { 1007 return hash ^ (value==null ? 0 : value.hashCode()); 1008 } 1009 1010 public String toString() { 1011 return key.toString()+"="+value.toString(); 1012 } 1013 } 1014 1015 // Types of Enumerations/Iterations 1016 private static final int KEYS = 0; 1017 private static final int VALUES = 1; 1018 private static final int ENTRIES = 2; 1019 1020 /** 1021 * A hashtable enumerator class. This class implements both the 1022 * Enumeration and Iterator interfaces, but individual instances 1023 * can be created with the Iterator methods disabled. This is necessary 1024 * to avoid unintentionally increasing the capabilities granted a user 1025 * by passing an Enumeration. 1026 */ 1027 private class Enumerator<T> implements Enumeration<T>, Iterator<T> { 1028 Entry<?,?>[] table = Hashtable.this.table; 1029 int index = table.length; 1030 Entry<?,?> entry = null; 1031 Entry<?,?> lastReturned = null; 1032 int type; 1033 1034 /** 1035 * Indicates whether this Enumerator is serving as an Iterator 1036 * or an Enumeration. (true -> Iterator). 1037 */ 1038 boolean iterator; 1039 1040 /** 1041 * The modCount value that the iterator believes that the backing 1042 * Hashtable should have. If this expectation is violated, the iterator 1043 * has detected concurrent modification. 1044 */ 1045 protected int expectedModCount = modCount; 1046 1047 Enumerator(int type, boolean iterator) { 1048 this.type = type; 1049 this.iterator = iterator; 1050 } 1051 1052 public boolean hasMoreElements() { 1053 Entry<?,?> e = entry; 1054 int i = index; 1055 Entry<?,?>[] t = table; 1056 /* Use locals for faster loop iteration */ 1057 while (e == null && i > 0) { 1058 e = t[--i]; 1059 } 1060 entry = e; 1061 index = i; 1062 return e != null; 1063 } 1064 1065 @SuppressWarnings("unchecked") 1066 public T nextElement() { 1067 Entry<?,?> et = entry; 1068 int i = index; 1069 Entry<?,?>[] t = table; 1070 /* Use locals for faster loop iteration */ 1071 while (et == null && i > 0) { 1072 et = t[--i]; 1073 } 1074 entry = et; 1075 index = i; 1076 if (et != null) { 1077 Entry<?,?> e = lastReturned = entry; 1078 entry = e.next; 1079 return type == KEYS ? (T)e.key : (type == VALUES ? (T)e.value : (T)e); 1080 } 1081 throw new NoSuchElementException("Hashtable Enumerator"); 1082 } 1083 1084 // Iterator methods 1085 public boolean hasNext() { 1086 return hasMoreElements(); 1087 } 1088 1089 public T next() { 1090 if (modCount != expectedModCount) 1091 throw new ConcurrentModificationException(); 1092 return nextElement(); 1093 } 1094 1095 public void remove() { 1096 if (!iterator) 1097 throw new UnsupportedOperationException(); 1098 if (lastReturned == null) 1099 throw new IllegalStateException("Hashtable Enumerator"); 1100 if (modCount != expectedModCount) 1101 throw new ConcurrentModificationException(); 1102 1103 synchronized(Hashtable.this) { 1104 Entry<?,?>[] tab = Hashtable.this.table; 1105 int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length; 1106 1107 for (@SuppressWarnings("unchecked") 1108 Entry<K,V> e = (Entry<K,V>)tab[index], prev = null; e != null; 1109 prev = e, e = e.next) { 1110 if (e == lastReturned) { 1111 modCount++; 1112 expectedModCount++; 1113 if (prev == null) 1114 tab[index] = e.next; 1115 else 1116 prev.next = e.next; 1117 count--; 1118 lastReturned = null; 1119 return; 1120 } 1121 } 1122 throw new ConcurrentModificationException(); 1123 } 1124 } 1125 } 1126 }