Hashtable.java 33.9 KB
Newer Older
1 2
/* Hashtable.java -- a class providing a basic hashtable data structure,
   mapping Object --> Object
3
   Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
Tom Tromey committed
4

5 6 7 8 9 10
This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
11

12 13 14 15 16 17 18 19 20 21
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Tom Tromey committed
38 39 40

package java.util;

41
import java.io.IOException;
Tom Tromey committed
42
import java.io.Serializable;
43 44
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
45 46 47 48

// NOTE: This implementation is very similar to that of HashMap. If you fix
// a bug in here, chances are you should make a similar change to the HashMap
// code.
Tom Tromey committed
49 50

/**
51 52
 * A class which implements a hashtable data structure.
 * <p>
53 54 55 56 57
 *
 * This implementation of Hashtable uses a hash-bucket approach. That is:
 * linear probing and rehashing is avoided; instead, each hashed value maps
 * to a simple linked-list which, in the best case, only has one node.
 * Assuming a large enough table, low enough load factor, and / or well
58
 * implemented hashCode() methods, Hashtable should provide O(1)
59
 * insertion, deletion, and searching of keys.  Hashtable is O(n) in
60 61
 * the worst case for all of these (if all keys hash to the same bucket).
 * <p>
62
 *
63
 * This is a JDK-1.2 compliant implementation of Hashtable.  As such, it
64
 * belongs, partially, to the Collections framework (in that it implements
65
 * Map).  For backwards compatibility, it inherits from the obsolete and
66
 * utterly useless Dictionary class.
67
 * <p>
68 69 70 71 72 73 74
 *
 * Being a hybrid of old and new, Hashtable has methods which provide redundant
 * capability, but with subtle and even crucial differences.
 * For example, one can iterate over various aspects of a Hashtable with
 * either an Iterator (which is the JDK-1.2 way of doing things) or with an
 * Enumeration.  The latter can end up in an undefined state if the Hashtable
 * changes while the Enumeration is open.
75 76 77 78 79
 * <p>
 *
 * Unlike HashMap, Hashtable does not accept `null' as a key value. Also,
 * all accesses are synchronized: in a single thread environment, this is
 * expensive, but in a multi-thread environment, this saves you the effort
80 81 82
 * of extra synchronization. However, the old-style enumerators are not
 * synchronized, because they can lead to unspecified behavior even if
 * they were synchronized. You have been warned.
83
 * <p>
84
 *
85 86 87 88 89
 * The iterators are <i>fail-fast</i>, meaning that any structural
 * modification, except for <code>remove()</code> called on the iterator
 * itself, cause the iterator to throw a
 * <code>ConcurrentModificationException</code> rather than exhibit
 * non-deterministic behavior.
90
 *
91 92 93 94 95 96 97 98 99
 * @author Jon Zeppieri
 * @author Warren Levy
 * @author Bryce McKinlay
 * @author Eric Blake <ebb9@email.byu.edu>
 * @see HashMap
 * @see TreeMap
 * @see IdentityHashMap
 * @see LinkedHashMap
 * @since 1.0
100
 * @status updated to 1.4
Tom Tromey committed
101
 */
102
public class Hashtable extends Dictionary
103
  implements Map, Cloneable, Serializable
Tom Tromey committed
104
{
105 106 107
  // WARNING: Hashtable is a CORE class in the bootstrap cycle. See the
  // comments in vm/reference/java/lang/Runtime for implications of this fact.

108 109 110 111 112
  /** Default number of buckets. This is the value the JDK 1.3 uses. Some
   * early documentation specified this value as 101. That is incorrect.
   */
  private static final int DEFAULT_CAPACITY = 11;

113 114 115 116 117 118
  /** An "enum" of iterator types. */
  // Package visible for use by nested classes.
  static final int KEYS = 0,
                   VALUES = 1,
                   ENTRIES = 2;

119 120 121
  /**
   * The default load factor; this is explicitly specified by the spec.
   */
122 123
  private static final float DEFAULT_LOAD_FACTOR = 0.75f;

124 125 126
  /**
   * Compatible with JDK 1.0+.
   */
127
  private static final long serialVersionUID = 1421746759512286392L;
128

129 130 131
  /**
   * The rounded product of the capacity and the load factor; when the number
   * of elements exceeds the threshold, the Hashtable calls
132
   * <code>rehash()</code>.
133 134
   * @serial
   */
135
  private int threshold;
136

137 138
  /**
   * Load factor of this Hashtable:  used in computing the threshold.
139 140
   * @serial
   */
141
  private final float loadFactor;
142

143 144
  /**
   * Array containing the actual key-value mappings.
145
   */
146
  // Package visible for use by nested classes.
147
  transient HashEntry[] buckets;
148

149 150 151
  /**
   * Counts the number of modifications this Hashtable has undergone, used
   * by Iterators to know when to throw ConcurrentModificationExceptions.
152
   */
153
  // Package visible for use by nested classes.
154 155
  transient int modCount;

156 157 158
  /**
   * The size of this Hashtable:  denotes the number of key-value pairs.
   */
159
  // Package visible for use by nested classes.
160 161 162
  transient int size;

  /**
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
   * The cache for {@link #keySet()}.
   */
  private transient Set keys;

  /**
   * The cache for {@link #values()}.
   */
  private transient Collection values;

  /**
   * The cache for {@link #entrySet()}.
   */
  private transient Set entries;

  /**
178 179
   * Class to represent an entry in the hash table. Holds a single key-value
   * pair. A Hashtable Entry is identical to a HashMap Entry, except that
180
   * `null' is not allowed for keys and values.
181
   */
182
  private static final class HashEntry extends AbstractMap.BasicMapEntry
183
  {
184 185 186 187 188 189 190 191 192
    /** The next entry in the linked list. */
    HashEntry next;

    /**
     * Simple constructor.
     * @param key the key, already guaranteed non-null
     * @param value the value, already guaranteed non-null
     */
    HashEntry(Object key, Object value)
193 194 195 196
    {
      super(key, value);
    }

197 198 199 200 201 202
    /**
     * Resets the value.
     * @param newValue the new value
     * @return the prior value
     * @throws NullPointerException if <code>newVal</code> is null
     */
203
    public Object setValue(Object newVal)
204 205 206 207 208 209 210 211
    {
      if (newVal == null)
        throw new NullPointerException();
      return super.setValue(newVal);
    }
  }

  /**
212
   * Construct a new Hashtable with the default capacity (11) and the default
213 214
   * load factor (0.75).
   */
215
  public Hashtable()
Tom Tromey committed
216
  {
217
    this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
Tom Tromey committed
218
  }
219

220
  /**
221 222 223
   * Construct a new Hashtable from the given Map, with initial capacity
   * the greater of the size of <code>m</code> or the default of 11.
   * <p>
224
   *
225 226 227 228 229 230 231 232
   * Every element in Map m will be put into this new Hashtable.
   *
   * @param m a Map whose key / value pairs will be put into
   *          the new Hashtable.  <b>NOTE: key / value pairs
   *          are not cloned in this constructor.</b>
   * @throws NullPointerException if m is null, or if m contains a mapping
   *         to or from `null'.
   * @since 1.2
233
   */
234
  public Hashtable(Map m)
Tom Tromey committed
235
  {
236
    this(Math.max(m.size() * 2, DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR);
237
    putAllInternal(m);
Tom Tromey committed
238
  }
239

240
  /**
241 242
   * Construct a new Hashtable with a specific inital capacity and
   * default load factor of 0.75.
243
   *
244 245
   * @param initialCapacity the initial capacity of this Hashtable (&gt;= 0)
   * @throws IllegalArgumentException if (initialCapacity &lt; 0)
246
   */
247
  public Hashtable(int initialCapacity)
Tom Tromey committed
248
  {
249
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
Tom Tromey committed
250
  }
251

252
  /**
253 254
   * Construct a new Hashtable with a specific initial capacity and
   * load factor.
255
   *
256 257 258 259
   * @param initialCapacity the initial capacity (&gt;= 0)
   * @param loadFactor the load factor (&gt; 0, not NaN)
   * @throws IllegalArgumentException if (initialCapacity &lt; 0) ||
   *                                     ! (loadFactor &gt; 0.0)
260
   */
261
  public Hashtable(int initialCapacity, float loadFactor)
Tom Tromey committed
262
  {
263
    if (initialCapacity < 0)
264 265 266 267 268
      throw new IllegalArgumentException("Illegal Capacity: "
                                         + initialCapacity);
    if (! (loadFactor > 0)) // check for NaN too
      throw new IllegalArgumentException("Illegal Load: " + loadFactor);

269
    if (initialCapacity == 0)
270 271
      initialCapacity = 1;
    buckets = new HashEntry[initialCapacity];
272
    this.loadFactor = loadFactor;
273
    threshold = (int) (initialCapacity * loadFactor);
Tom Tromey committed
274
  }
275

276 277 278 279 280
  /**
   * Returns the number of key-value mappings currently in this hashtable.
   * @return the size
   */
  public synchronized int size()
Tom Tromey committed
281
  {
282
    return size;
Tom Tromey committed
283
  }
284

285 286 287 288 289
  /**
   * Returns true if there are no key-value mappings currently in this table.
   * @return <code>size() == 0</code>
   */
  public synchronized boolean isEmpty()
Tom Tromey committed
290
  {
291
    return size == 0;
Tom Tromey committed
292
  }
293

294
  /**
295 296 297 298
   * Return an enumeration of the keys of this table. There's no point
   * in synchronizing this, as you have already been warned that the
   * enumeration is not specified to be thread-safe.
   *
299 300 301 302
   * @return the keys
   * @see #elements()
   * @see #keySet()
   */
303
  public Enumeration keys()
Tom Tromey committed
304
  {
305
    return new Enumerator(KEYS);
Tom Tromey committed
306
  }
307 308

  /**
309 310 311 312
   * Return an enumeration of the values of this table. There's no point
   * in synchronizing this, as you have already been warned that the
   * enumeration is not specified to be thread-safe.
   *
313 314 315 316
   * @return the values
   * @see #keys()
   * @see #values()
   */
317
  public Enumeration elements()
Tom Tromey committed
318
  {
319
    return new Enumerator(VALUES);
Tom Tromey committed
320
  }
321

322
  /**
323 324
   * Returns true if this Hashtable contains a value <code>o</code>,
   * such that <code>o.equals(value)</code>.  This is the same as
325 326
   * <code>containsValue()</code>, and is O(n).
   * <p>
327
   *
328 329
   * @param value the value to search for in this Hashtable
   * @return true if at least one key maps to the value
330
   * @throws NullPointerException if <code>value</code> is null
331 332
   * @see #containsValue(Object)
   * @see #containsKey(Object)
333 334
   */
  public synchronized boolean contains(Object value)
335
  {
336
    return containsValue(value);
Tom Tromey committed
337
  }
338

339
  /**
340 341
   * Returns true if this Hashtable contains a value <code>o</code>, such that
   * <code>o.equals(value)</code>. This is the new API for the old
342
   * <code>contains()</code>.
343
   *
344 345 346 347
   * @param value the value to search for in this Hashtable
   * @return true if at least one key maps to the value
   * @see #contains(Object)
   * @see #containsKey(Object)
348
   * @throws NullPointerException if <code>value</code> is null
349
   * @since 1.2
350 351
   */
  public boolean containsValue(Object value)
Tom Tromey committed
352
  {
353 354 355 356 357
    for (int i = buckets.length - 1; i >= 0; i--)
      {
        HashEntry e = buckets[i];
        while (e != null)
          {
358
            if (value.equals(e.value))
359 360 361 362
              return true;
            e = e.next;
          }
      }
363 364 365 366

    // Must throw on null argument even if the table is empty
    if (value == null)
      throw new NullPointerException();
367
 
368
    return false;
Tom Tromey committed
369
  }
370

371
  /**
372
   * Returns true if the supplied object <code>equals()</code> a key
373
   * in this Hashtable.
374
   *
375 376 377 378
   * @param key the key to search for in this Hashtable
   * @return true if the key is in the table
   * @throws NullPointerException if key is null
   * @see #containsValue(Object)
379 380
   */
  public synchronized boolean containsKey(Object key)
Tom Tromey committed
381
  {
382
    int idx = hash(key);
383
    HashEntry e = buckets[idx];
384
    while (e != null)
385
      {
386
        if (key.equals(e.key))
387 388
          return true;
        e = e.next;
389
      }
390
    return false;
Tom Tromey committed
391
  }
392 393

  /**
394
   * Return the value in this Hashtable associated with the supplied key,
395
   * or <code>null</code> if the key maps to nothing.
396
   *
397 398 399 400 401
   * @param key the key for which to fetch an associated value
   * @return what the key maps to, if present
   * @throws NullPointerException if key is null
   * @see #put(Object, Object)
   * @see #containsKey(Object)
402
   */
Tom Tromey committed
403 404
  public synchronized Object get(Object key)
  {
405
    int idx = hash(key);
406
    HashEntry e = buckets[idx];
407
    while (e != null)
408
      {
409
        if (key.equals(e.key))
410 411
          return e.value;
        e = e.next;
412
      }
413
    return null;
Tom Tromey committed
414
  }
415 416

  /**
417 418 419
   * Puts the supplied value into the Map, mapped by the supplied key.
   * Neither parameter may be null.  The value may be retrieved by any
   * object which <code>equals()</code> this key.
420
   *
421 422 423 424 425 426
   * @param key the key used to locate the value
   * @param value the value to be stored in the table
   * @return the prior mapping of the key, or null if there was none
   * @throws NullPointerException if key or value is null
   * @see #get(Object)
   * @see Object#equals(Object)
427 428
   */
  public synchronized Object put(Object key, Object value)
Tom Tromey committed
429
  {
430
    int idx = hash(key);
431 432 433
    HashEntry e = buckets[idx];

    // Check if value is null since it is not permitted.
434 435 436 437
    if (value == null)
      throw new NullPointerException();

    while (e != null)
438
      {
439
        if (key.equals(e.key))
440 441 442 443 444 445 446 447 448 449
          {
            // Bypass e.setValue, since we already know value is non-null.
            Object r = e.value;
            e.value = value;
            return r;
          }
        else
          {
            e = e.next;
          }
450
      }
451

452
    // At this point, we know we need to add a new entry.
453
    modCount++;
454
    if (++size > threshold)
455
      {
456 457 458
        rehash();
        // Need a new hash value to suit the bigger table.
        idx = hash(key);
459
      }
460

461 462
    e = new HashEntry(key, value);

463 464
    e.next = buckets[idx];
    buckets[idx] = e;
465

466
    return null;
Tom Tromey committed
467
  }
468

469
  /**
470 471
   * Removes from the table and returns the value which is mapped by the
   * supplied key. If the key maps to nothing, then the table remains
472
   * unchanged, and <code>null</code> is returned.
473
   *
474 475
   * @param key the key used to locate the value to remove
   * @return whatever the key mapped to, if present
476
   */
477
  public synchronized Object remove(Object key)
Tom Tromey committed
478
  {
479
    int idx = hash(key);
480 481
    HashEntry e = buckets[idx];
    HashEntry last = null;
482 483

    while (e != null)
484
      {
485
        if (key.equals(e.key))
486
          {
487
            modCount++;
488 489 490 491 492 493 494 495 496
            if (last == null)
              buckets[idx] = e.next;
            else
              last.next = e.next;
            size--;
            return e.value;
          }
        last = e;
        e = e.next;
497
      }
498
    return null;
499
  }
500

501 502 503 504 505 506 507 508
  /**
   * Copies all elements of the given map into this hashtable.  However, no
   * mapping can contain null as key or value.  If this table already has
   * a mapping for a key, the new mapping replaces the current one.
   *
   * @param m the map to be hashed into this
   * @throws NullPointerException if m is null, or contains null keys or values
   */
509
  public synchronized void putAll(Map m)
510
  {
511
    Iterator itr = m.entrySet().iterator();
512 513

    for (int msize = m.size(); msize > 0; msize--)
514
      {
515
        Map.Entry e = (Map.Entry) itr.next();
516
        // Optimize in case the Entry is one of our own.
517
        if (e instanceof AbstractMap.BasicMapEntry)
518
          {
519
            AbstractMap.BasicMapEntry entry = (AbstractMap.BasicMapEntry) e;
520 521 522 523
            put(entry.key, entry.value);
          }
        else
          {
524
            put(e.getKey(), e.getValue());
525
          }
526 527
      }
  }
528 529 530 531

  /**
   * Clears the hashtable so it has no keys.  This is O(1).
   */
532 533
  public synchronized void clear()
  {
534 535 536 537 538 539
    if (size > 0)
      {
        modCount++;
        Arrays.fill(buckets, null);
        size = 0;
      }
540
  }
541

542 543 544 545 546
  /**
   * Returns a shallow clone of this Hashtable. The Map itself is cloned,
   * but its contents are not.  This is O(n).
   *
   * @return the clone
547
   */
548 549
  public synchronized Object clone()
  {
550 551 552 553 554 555 556
    Hashtable copy = null;
    try
      {
        copy = (Hashtable) super.clone();
      }
    catch (CloneNotSupportedException x)
      {
557
        // This is impossible.
558
      }
559
    copy.buckets = new HashEntry[buckets.length];
560 561 562 563 564
    copy.putAllInternal(this);
    // Clear the caches.
    copy.keys = null;
    copy.values = null;
    copy.entries = null;
565
    return copy;
566
  }
567 568

  /**
569 570 571
   * Converts this Hashtable to a String, surrounded by braces, and with
   * key/value pairs listed with an equals sign between, separated by a
   * comma and space. For example, <code>"{a=1, b=2}"</code>.<p>
572 573 574 575 576 577
   *
   * NOTE: if the <code>toString()</code> method of any key or value
   * throws an exception, this will fail for the same reason.
   *
   * @return the string representation
   */
578 579
  public synchronized String toString()
  {
580 581 582
    // Since we are already synchronized, and entrySet().iterator()
    // would repeatedly re-lock/release the monitor, we directly use the
    // unsynchronized HashIterator instead.
583
    Iterator entries = new HashIterator(ENTRIES);
584
    StringBuffer r = new StringBuffer("{");
585
    for (int pos = size; pos > 0; pos--)
586
      {
587
        r.append(entries.next());
588 589
        if (pos > 1)
          r.append(", ");
590
      }
591
    r.append("}");
592
    return r.toString();
593
  }
594

595 596 597 598
  /**
   * Returns a "set view" of this Hashtable's keys. The set is backed by
   * the hashtable, so changes in one show up in the other.  The set supports
   * element removal, but not element addition.  The set is properly
599 600 601 602 603
   * synchronized on the original hashtable.  Sun has not documented the
   * proper interaction of null with this set, but has inconsistent behavior
   * in the JDK. Therefore, in this implementation, contains, remove,
   * containsAll, retainAll, removeAll, and equals just ignore a null key
   * rather than throwing a {@link NullPointerException}.
604 605 606 607 608 609
   *
   * @return a set view of the keys
   * @see #values()
   * @see #entrySet()
   * @since 1.2
   */
610
  public Set keySet()
611
  {
612
    if (keys == null)
613
      {
614 615 616 617 618 619 620 621
        // Create a synchronized AbstractSet with custom implementations of
        // those methods that can be overridden easily and efficiently.
        Set r = new AbstractSet()
        {
          public int size()
          {
            return size;
          }
622

623 624 625 626
          public Iterator iterator()
          {
            return new HashIterator(KEYS);
          }
627

628 629 630 631
          public void clear()
          {
            Hashtable.this.clear();
          }
632

633 634 635 636 637 638
          public boolean contains(Object o)
          {
            if (o == null)
              return false;
            return containsKey(o);
          }
639

640 641 642 643 644 645 646 647
          public boolean remove(Object o)
          {
            return Hashtable.this.remove(o) != null;
          }
        };
        // We must specify the correct object to synchronize upon, hence the
        // use of a non-public API
        keys = new Collections.SynchronizedSet(this, r);
648
      }
649
    return keys;
650
  }
651 652 653 654 655 656

  /**
   * Returns a "collection view" (or "bag view") of this Hashtable's values.
   * The collection is backed by the hashtable, so changes in one show up
   * in the other.  The collection supports element removal, but not element
   * addition.  The collection is properly synchronized on the original
657 658 659 660 661
   * hashtable.  Sun has not documented the proper interaction of null with
   * this set, but has inconsistent behavior in the JDK. Therefore, in this
   * implementation, contains, remove, containsAll, retainAll, removeAll, and
   * equals just ignore a null value rather than throwing a
   * {@link NullPointerException}.
662 663 664 665 666 667
   *
   * @return a bag view of the values
   * @see #keySet()
   * @see #entrySet()
   * @since 1.2
   */
668
  public Collection values()
669
  {
670
    if (values == null)
671
      {
672 673 674 675 676 677 678 679
        // We don't bother overriding many of the optional methods, as doing so
        // wouldn't provide any significant performance advantage.
        Collection r = new AbstractCollection()
        {
          public int size()
          {
            return size;
          }
680

681 682 683 684
          public Iterator iterator()
          {
            return new HashIterator(VALUES);
          }
685

686 687 688 689 690 691 692 693
          public void clear()
          {
            Hashtable.this.clear();
          }
        };
        // We must specify the correct object to synchronize upon, hence the
        // use of a non-public API
        values = new Collections.SynchronizedCollection(this, r);
694
      }
695
    return values;
696
  }
697

698 699 700 701
  /**
   * Returns a "set view" of this Hashtable's entries. The set is backed by
   * the hashtable, so changes in one show up in the other.  The set supports
   * element removal, but not element addition.  The set is properly
702 703 704 705 706 707 708
   * synchronized on the original hashtable.  Sun has not documented the
   * proper interaction of null with this set, but has inconsistent behavior
   * in the JDK. Therefore, in this implementation, contains, remove,
   * containsAll, retainAll, removeAll, and equals just ignore a null entry,
   * or an entry with a null key or value, rather than throwing a
   * {@link NullPointerException}. However, calling entry.setValue(null)
   * will fail.
709 710 711 712 713 714 715 716 717 718 719
   * <p>
   *
   * Note that the iterators for all three views, from keySet(), entrySet(),
   * and values(), traverse the hashtable in the same sequence.
   *
   * @return a set view of the entries
   * @see #keySet()
   * @see #values()
   * @see Map.Entry
   * @since 1.2
   */
720
  public Set entrySet()
721
  {
722
    if (entries == null)
723
      {
724 725 726 727 728 729 730 731
        // Create an AbstractSet with custom implementations of those methods
        // that can be overridden easily and efficiently.
        Set r = new AbstractSet()
        {
          public int size()
          {
            return size;
          }
732

733 734 735 736
          public Iterator iterator()
          {
            return new HashIterator(ENTRIES);
          }
737

738 739 740 741
          public void clear()
          {
            Hashtable.this.clear();
          }
742

743 744 745 746
          public boolean contains(Object o)
          {
            return getEntry(o) != null;
          }
747

748
          public boolean remove(Object o)
749
          {
750 751 752 753 754 755 756
            HashEntry e = getEntry(o);
            if (e != null)
              {
                Hashtable.this.remove(e.key);
                return true;
              }
            return false;
757
          }
758 759 760 761
        };
        // We must specify the correct object to synchronize upon, hence the
        // use of a non-public API
        entries = new Collections.SynchronizedSet(this, r);
762
      }
763
    return entries;
764
  }
765 766

  /**
767
   * Returns true if this Hashtable equals the supplied Object <code>o</code>.
768
   * As specified by Map, this is:
769
   * <code>
770
   * (o instanceof Map) && entrySet().equals(((Map) o).entrySet());
771
   * </code>
772 773 774 775
   *
   * @param o the object to compare to
   * @return true if o is an equal map
   * @since 1.2
776
   */
777
  public boolean equals(Object o)
778
  {
779
    // no need to synchronize, entrySet().equals() does that
780 781 782 783 784
    if (o == this)
      return true;
    if (!(o instanceof Map))
      return false;

785
    return entrySet().equals(((Map) o).entrySet());
786
  }
787 788 789 790 791 792 793 794 795

  /**
   * Returns the hashCode for this Hashtable.  As specified by Map, this is
   * the sum of the hashCodes of all of its Map.Entry objects
   *
   * @return the sum of the hashcodes of the entries
   * @since 1.2
   */
  public synchronized int hashCode()
796
  {
797 798 799
    // Since we are already synchronized, and entrySet().iterator()
    // would repeatedly re-lock/release the monitor, we directly use the
    // unsynchronized HashIterator instead.
800
    Iterator itr = new HashIterator(ENTRIES);
801
    int hashcode = 0;
802 803 804 805
    for (int pos = size; pos > 0; pos--)
      hashcode += itr.next().hashCode();

    return hashcode;
806
  }
807 808 809 810 811 812 813 814 815

  /**
   * Helper method that returns an index in the buckets array for `key'
   * based on its hashCode().
   *
   * @param key the key
   * @return the bucket number
   * @throws NullPointerException if key is null
   */
816 817
  private int hash(Object key)
  {
818 819 820 821
    // Note: Inline Math.abs here, for less method overhead, and to avoid
    // a bootstrap dependency, since Math relies on native methods.
    int hash = key.hashCode() % buckets.length;
    return hash < 0 ? -hash : hash;
822
  }
823

824 825
  /**
   * Helper method for entrySet(), which matches both key and value
826
   * simultaneously. Ignores null, as mentioned in entrySet().
827 828 829 830 831
   *
   * @param o the entry to match
   * @return the matching entry, if found, or null
   * @see #entrySet()
   */
832 833
  // Package visible, for use in nested classes.
  HashEntry getEntry(Object o)
834
  {
835 836 837 838
    if (! (o instanceof Map.Entry))
      return null;
    Object key = ((Map.Entry) o).getKey();
    if (key == null)
839
      return null;
840 841

    int idx = hash(key);
842
    HashEntry e = buckets[idx];
843
    while (e != null)
844
      {
845
        if (o.equals(e))
846 847
          return e;
        e = e.next;
848
      }
849
    return null;
850
  }
851 852

  /**
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
   * A simplified, more efficient internal implementation of putAll(). The 
   * Map constructor and clone() should not call putAll or put, in order to 
   * be compatible with the JDK implementation with respect to subclasses.
   *
   * @param m the map to initialize this from
   */
  void putAllInternal(Map m)
  {
    Iterator itr = m.entrySet().iterator();
    int msize = m.size();
    this.size = msize;

    for (; msize > 0; msize--)
      {
	Map.Entry e = (Map.Entry) itr.next();
	Object key = e.getKey();
	int idx = hash(key);
	HashEntry he = new HashEntry(key, e.getValue());
	he.next = buckets[idx];
	buckets[idx] = he;
      }
  }

  /**
877 878
   * Increases the size of the Hashtable and rehashes all keys to new array
   * indices; this is called when the addition of a new value would cause
879
   * size() &gt; threshold. Note that the existing Entry objects are reused in
880
   * the new hash table.
881 882 883
   * <p>
   *
   * This is not specified, but the new size is twice the current size plus
884 885
   * one; this number is not always prime, unfortunately. This implementation
   * is not synchronized, as it is only invoked from synchronized methods.
886 887
   */
  protected void rehash()
888
  {
889 890
    HashEntry[] oldBuckets = buckets;

891 892
    int newcapacity = (buckets.length * 2) + 1;
    threshold = (int) (newcapacity * loadFactor);
893 894 895
    buckets = new HashEntry[newcapacity];

    for (int i = oldBuckets.length - 1; i >= 0; i--)
896
      {
897
        HashEntry e = oldBuckets[i];
898
        while (e != null)
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
          {
            int idx = hash(e.key);
            HashEntry dest = buckets[idx];

            if (dest != null)
              {
                while (dest.next != null)
                  dest = dest.next;
                dest.next = e;
              }
            else
              {
                buckets[idx] = e;
              }

            HashEntry next = e.next;
            e.next = null;
            e = next;
          }
918 919
      }
  }
920

921
  /**
922
   * Serializes this object to the given stream.
923 924 925
   *
   * @param s the stream to write to
   * @throws IOException if the underlying stream fails
926 927
   * @serialData the <i>capacity</i> (int) that is the length of the
   *             bucket array, the <i>size</i> (int) of the hash map
928 929
   *             are emitted first.  They are followed by size entries,
   *             each consisting of a key (Object) and a value (Object).
930
   */
931 932
  private synchronized void writeObject(ObjectOutputStream s)
    throws IOException
933
  {
934
    // Write the threshold and loadFactor fields.
935 936 937 938
    s.defaultWriteObject();

    s.writeInt(buckets.length);
    s.writeInt(size);
939 940 941
    // Since we are already synchronized, and entrySet().iterator()
    // would repeatedly re-lock/release the monitor, we directly use the
    // unsynchronized HashIterator instead.
942
    Iterator it = new HashIterator(ENTRIES);
943 944
    while (it.hasNext())
      {
945 946 947
        HashEntry entry = (HashEntry) it.next();
        s.writeObject(entry.key);
        s.writeObject(entry.value);
948
      }
949
  }
950

951
  /**
952
   * Deserializes this object from the given stream.
953 954 955 956
   *
   * @param s the stream to read from
   * @throws ClassNotFoundException if the underlying stream fails
   * @throws IOException if the underlying stream fails
957 958
   * @serialData the <i>capacity</i> (int) that is the length of the
   *             bucket array, the <i>size</i> (int) of the hash map
959 960
   *             are emitted first.  They are followed by size entries,
   *             each consisting of a key (Object) and a value (Object).
961
   */
962 963
  private void readObject(ObjectInputStream s)
    throws IOException, ClassNotFoundException
Tom Tromey committed
964
  {
965
    // Read the threshold and loadFactor fields.
966 967
    s.defaultReadObject();

968 969
    // Read and use capacity.
    buckets = new HashEntry[s.readInt()];
970 971
    int len = s.readInt();

972
    // Read and use key/value pairs.
973 974
    // TODO: should we be defensive programmers, and check for illegal nulls?
    while (--len >= 0)
975
      put(s.readObject(), s.readObject());
Tom Tromey committed
976
  }
977

978
  /**
979 980 981 982 983 984 985
   * A class which implements the Iterator interface and is used for
   * iterating over Hashtables.
   * This implementation is parameterized to give a sequential view of
   * keys, values, or entries; it also allows the removal of elements,
   * as per the Javasoft spec.  Note that it is not synchronized; this is
   * a performance enhancer since it is never exposed externally and is
   * only used within synchronized blocks above.
986
   *
987
   * @author Jon Zeppieri
988
   */
989
  private final class HashIterator implements Iterator
990
  {
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    /**
     * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
     * or {@link #ENTRIES}.
     */
    final int type;
    /**
     * The number of modifications to the backing Hashtable that we know about.
     */
    int knownMod = modCount;
    /** The number of elements remaining to be returned by next(). */
    int count = size;
    /** Current index in the physical hash table. */
    int idx = buckets.length;
    /** The last Entry returned by a next() call. */
    HashEntry last;
    /**
     * The next entry that should be returned by next(). It is set to something
     * if we're iterating through a bucket that contains multiple linked
     * entries. It is null if next() needs to find a new bucket.
     */
    HashEntry next;

    /**
     * Construct a new HashIterator with the supplied type.
     * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
     */
1017
    HashIterator(int type)
Tom Tromey committed
1018
    {
1019
      this.type = type;
Tom Tromey committed
1020
    }
1021

1022 1023 1024 1025 1026
    /**
     * Returns true if the Iterator has more elements.
     * @return true if there are more elements
     * @throws ConcurrentModificationException if the hashtable was modified
     */
1027
    public boolean hasNext()
Tom Tromey committed
1028
    {
1029 1030 1031
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
      return count > 0;
Tom Tromey committed
1032
    }
1033

1034 1035 1036 1037 1038 1039
    /**
     * Returns the next element in the Iterator's sequential view.
     * @return the next element
     * @throws ConcurrentModificationException if the hashtable was modified
     * @throws NoSuchElementException if there is none
     */
1040
    public Object next()
Tom Tromey committed
1041
    {
1042 1043 1044
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
      if (count == 0)
1045
        throw new NoSuchElementException();
1046 1047
      count--;
      HashEntry e = next;
1048 1049

      while (e == null)
1050
        e = buckets[--idx];
1051 1052 1053 1054 1055

      next = e.next;
      last = e;
      if (type == VALUES)
        return e.value;
1056
      if (type == KEYS)
1057 1058
        return e.key;
      return e;
1059
    }
1060

1061 1062
    /**
     * Removes from the backing Hashtable the last element which was fetched
1063
     * with the <code>next()</code> method.
1064 1065
     * @throws ConcurrentModificationException if the hashtable was modified
     * @throws IllegalStateException if called when there is no last element
1066
     */
1067 1068
    public void remove()
    {
1069 1070
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
1071
      if (last == null)
1072 1073 1074 1075
        throw new IllegalStateException();

      Hashtable.this.remove(last.key);
      last = null;
1076
      knownMod++;
Tom Tromey committed
1077
    }
1078
  } // class HashIterator
Tom Tromey committed
1079 1080


1081
  /**
1082 1083
   * Enumeration view of this Hashtable, providing sequential access to its
   * elements; this implementation is parameterized to provide access either
1084 1085
   * to the keys or to the values in the Hashtable.
   *
1086 1087
   * <b>NOTE</b>: Enumeration is not safe if new elements are put in the table
   * as this could cause a rehash and we'd completely lose our place.  Even
1088 1089 1090 1091 1092
   * without a rehash, it is undetermined if a new element added would
   * appear in the enumeration.  The spec says nothing about this, but
   * the "Java Class Libraries" book infers that modifications to the
   * hashtable during enumeration causes indeterminate results.  Don't do it!
   *
1093
   * @author Jon Zeppieri
1094
   */
1095
  private final class Enumerator implements Enumeration
1096
  {
1097 1098 1099
    /**
     * The type of this Iterator: {@link #KEYS} or {@link #VALUES}.
     */
1100 1101 1102
    final int type;
    /** The number of elements remaining to be returned by next(). */
    int count = size;
1103
    /** Current index in the physical hash table. */
1104 1105 1106 1107 1108 1109
    int idx = buckets.length;
    /**
     * Entry which will be returned by the next nextElement() call. It is
     * set if we are iterating through a bucket with multiple entries, or null
     * if we must look in the next bucket.
     */
1110 1111 1112 1113 1114 1115
    HashEntry next;

    /**
     * Construct the enumeration.
     * @param type either {@link #KEYS} or {@link #VALUES}.
     */
1116 1117 1118
    Enumerator(int type)
    {
      this.type = type;
1119
    }
Tom Tromey committed
1120

1121 1122 1123 1124
    /**
     * Checks whether more elements remain in the enumeration.
     * @return true if nextElement() will not fail.
     */
1125 1126
    public boolean hasMoreElements()
    {
1127
      return count > 0;
1128
    }
Tom Tromey committed
1129

1130 1131 1132 1133 1134
    /**
     * Returns the next element.
     * @return the next element
     * @throws NoSuchElementException if there is none.
     */
1135 1136
    public Object nextElement()
    {
1137
      if (count == 0)
1138
        throw new NoSuchElementException("Hashtable Enumerator");
1139 1140 1141 1142 1143 1144 1145 1146
      count--;
      HashEntry e = next;

      while (e == null)
        e = buckets[--idx];

      next = e.next;
      return type == VALUES ? e.value : e.key;
1147
    }
1148
  } // class Enumerator
1149
} // class Hashtable