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, 2004, 2005  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 42 43
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
Dalibor Topic committed
44
import java.io.Serializable;
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
 * @author Jon Zeppieri
 * @author Warren Levy
 * @author Bryce McKinlay
94
 * @author Eric Blake (ebb9@email.byu.edu)
95 96 97 98 99
 * @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
    putAll(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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    for (int i = buckets.length - 1; i >= 0; i--)
      {
        HashEntry e = buckets[i];
        while (e != null)
          {
            if (value.equals(e.value))
              return true;
            e = e.next;
          }
      }

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

354
  /**
355 356
   * 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
357
   * <code>contains()</code>.
358
   *
359 360 361 362
   * @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)
363
   * @throws NullPointerException if <code>value</code> is null
364
   * @since 1.2
365 366
   */
  public boolean containsValue(Object value)
Tom Tromey committed
367
  {
368 369
    // Delegate to older method to make sure code overriding it continues 
    // to work.
370 371 372 373
    return contains(value);
  }

  /**
374
   * Returns true if the supplied object <code>equals()</code> a key
375
   * in this Hashtable.
376
   *
377 378 379 380
   * @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)
381 382
   */
  public synchronized boolean containsKey(Object key)
Tom Tromey committed
383
  {
384
    int idx = hash(key);
385
    HashEntry e = buckets[idx];
386
    while (e != null)
387
      {
388
        if (key.equals(e.key))
389 390
          return true;
        e = e.next;
391
      }
392
    return false;
Tom Tromey committed
393
  }
394 395

  /**
396
   * Return the value in this Hashtable associated with the supplied key,
397
   * or <code>null</code> if the key maps to nothing.
398
   *
399 400 401 402 403
   * @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)
404
   */
Tom Tromey committed
405 406
  public synchronized Object get(Object key)
  {
407
    int idx = hash(key);
408
    HashEntry e = buckets[idx];
409
    while (e != null)
410
      {
411
        if (key.equals(e.key))
412 413
          return e.value;
        e = e.next;
414
      }
415
    return null;
Tom Tromey committed
416
  }
417 418

  /**
419 420 421
   * 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.
422
   *
423 424 425 426 427 428
   * @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)
429 430
   */
  public synchronized Object put(Object key, Object value)
Tom Tromey committed
431
  {
432
    int idx = hash(key);
433 434 435
    HashEntry e = buckets[idx];

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

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

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

463 464
    e = new HashEntry(key, value);

465 466
    e.next = buckets[idx];
    buckets[idx] = e;
467

468
    return null;
Tom Tromey committed
469
  }
470

471
  /**
472 473
   * 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
474
   * unchanged, and <code>null</code> is returned.
475
   *
476 477
   * @param key the key used to locate the value to remove
   * @return whatever the key mapped to, if present
478
   */
479
  public synchronized Object remove(Object key)
Tom Tromey committed
480
  {
481
    int idx = hash(key);
482 483
    HashEntry e = buckets[idx];
    HashEntry last = null;
484 485

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

503 504 505 506 507 508 509 510
  /**
   * 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
   */
511
  public synchronized void putAll(Map m)
512
  {
513
    Iterator itr = m.entrySet().iterator();
514

515
    while (itr.hasNext())
516
      {
517
        Map.Entry e = (Map.Entry) itr.next();
518
        // Optimize in case the Entry is one of our own.
519
        if (e instanceof AbstractMap.BasicMapEntry)
520
          {
521
            AbstractMap.BasicMapEntry entry = (AbstractMap.BasicMapEntry) e;
522 523 524 525
            put(entry.key, entry.value);
          }
        else
          {
526
            put(e.getKey(), e.getValue());
527
          }
528 529
      }
  }
530 531 532 533

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

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

  /**
571 572 573
   * 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>
574 575 576 577 578 579
   *
   * 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
   */
580 581
  public synchronized String toString()
  {
582 583 584
    // Since we are already synchronized, and entrySet().iterator()
    // would repeatedly re-lock/release the monitor, we directly use the
    // unsynchronized HashIterator instead.
585
    Iterator entries = new HashIterator(ENTRIES);
586
    StringBuffer r = new StringBuffer("{");
587
    for (int pos = size; pos > 0; pos--)
588
      {
589
        r.append(entries.next());
590 591
        if (pos > 1)
          r.append(", ");
592
      }
593
    r.append("}");
594
    return r.toString();
595
  }
596

597 598 599 600
  /**
   * 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
601 602 603 604 605
   * 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}.
606 607 608 609 610 611
   *
   * @return a set view of the keys
   * @see #values()
   * @see #entrySet()
   * @since 1.2
   */
612
  public Set keySet()
613
  {
614
    if (keys == null)
615
      {
616 617 618 619 620 621 622 623
        // 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;
          }
624

625 626 627 628
          public Iterator iterator()
          {
            return new HashIterator(KEYS);
          }
629

630 631 632 633
          public void clear()
          {
            Hashtable.this.clear();
          }
634

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

642 643 644 645 646 647 648 649
          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);
650
      }
651
    return keys;
652
  }
653 654 655 656 657 658

  /**
   * 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
659 660 661 662 663
   * 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}.
664 665 666 667 668 669
   *
   * @return a bag view of the values
   * @see #keySet()
   * @see #entrySet()
   * @since 1.2
   */
670
  public Collection values()
671
  {
672
    if (values == null)
673
      {
674 675 676 677 678 679 680 681
        // 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;
          }
682

683 684 685 686
          public Iterator iterator()
          {
            return new HashIterator(VALUES);
          }
687

688 689 690 691 692 693 694 695
          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);
696
      }
697
    return values;
698
  }
699

700 701 702 703
  /**
   * 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
704 705 706 707 708 709 710
   * 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.
711 712 713 714 715 716 717 718 719 720 721
   * <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
   */
722
  public Set entrySet()
723
  {
724
    if (entries == null)
725
      {
726 727 728 729 730 731 732 733
        // 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;
          }
734

735 736 737 738
          public Iterator iterator()
          {
            return new HashIterator(ENTRIES);
          }
739

740 741 742 743
          public void clear()
          {
            Hashtable.this.clear();
          }
744

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

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

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

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

  /**
   * 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()
798
  {
799 800 801
    // Since we are already synchronized, and entrySet().iterator()
    // would repeatedly re-lock/release the monitor, we directly use the
    // unsynchronized HashIterator instead.
802
    Iterator itr = new HashIterator(ENTRIES);
803
    int hashcode = 0;
804 805 806 807
    for (int pos = size; pos > 0; pos--)
      hashcode += itr.next().hashCode();

    return hashcode;
808
  }
809 810 811 812 813 814 815 816 817

  /**
   * 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
   */
818 819
  private int hash(Object key)
  {
820 821 822 823
    // 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;
824
  }
825

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

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

  /**
855 856 857
   * A simplified, more efficient internal implementation of putAll(). clone() 
   * should not call putAll or put, in order to be compatible with the JDK 
   * implementation with respect to subclasses.
858 859 860 861 862 863
   *
   * @param m the map to initialize this from
   */
  void putAllInternal(Map m)
  {
    Iterator itr = m.entrySet().iterator();
864
    size = 0;
865

866
    while (itr.hasNext())
867
      {
868
        size++;
869 870 871 872 873 874 875 876 877 878
	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;
      }
  }

  /**
879 880
   * 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
881
   * size() &gt; threshold. Note that the existing Entry objects are reused in
882
   * the new hash table.
883 884 885
   * <p>
   *
   * This is not specified, but the new size is twice the current size plus
886 887
   * one; this number is not always prime, unfortunately. This implementation
   * is not synchronized, as it is only invoked from synchronized methods.
888 889
   */
  protected void rehash()
890
  {
891 892
    HashEntry[] oldBuckets = buckets;

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

    for (int i = oldBuckets.length - 1; i >= 0; i--)
898
      {
899
        HashEntry e = oldBuckets[i];
900
        while (e != null)
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
          {
            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;
          }
920 921
      }
  }
922

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

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

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

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

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

980
  /**
981 982 983 984 985 986 987
   * 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.
988
   *
989
   * @author Jon Zeppieri
990
   */
991
  private final class HashIterator implements Iterator
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 1017 1018
    /**
     * 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}
     */
1019
    HashIterator(int type)
Tom Tromey committed
1020
    {
1021
      this.type = type;
Tom Tromey committed
1022
    }
1023

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

1036 1037 1038 1039 1040 1041
    /**
     * 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
     */
1042
    public Object next()
Tom Tromey committed
1043
    {
1044 1045 1046
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
      if (count == 0)
1047
        throw new NoSuchElementException();
1048 1049
      count--;
      HashEntry e = next;
1050 1051

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

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

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

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


1083
  /**
1084 1085
   * Enumeration view of this Hashtable, providing sequential access to its
   * elements; this implementation is parameterized to provide access either
1086 1087
   * to the keys or to the values in the Hashtable.
   *
1088 1089
   * <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
1090 1091 1092 1093 1094
   * 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!
   *
1095
   * @author Jon Zeppieri
1096
   */
1097
  private final class Enumerator implements Enumeration
1098
  {
1099 1100 1101
    /**
     * The type of this Iterator: {@link #KEYS} or {@link #VALUES}.
     */
1102 1103 1104
    final int type;
    /** The number of elements remaining to be returned by next(). */
    int count = size;
1105
    /** Current index in the physical hash table. */
1106 1107 1108 1109 1110 1111
    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.
     */
1112 1113 1114 1115 1116 1117
    HashEntry next;

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

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

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

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

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