HashMap.java 23.9 KB
Newer Older
1 2
/* HashMap.java -- a class providing a basic hashtable data structure,
   mapping Object --> Object
Bryce McKinlay committed
3
   Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
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 22 23 24 25 26 27 28 29 30 31 32 33 34
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.

As a special exception, if you link this library with other files to
produce an executable, this library does not by itself cause the
resulting executable to be covered by the GNU General Public License.
This exception does not however invalidate any other reasons why the
executable file might be covered by the GNU General Public License. */


package java.util;

import java.io.IOException;
import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
35 36 37 38

// NOTE: This implementation is very similar to that of Hashtable. If you fix
// a bug in here, chances are you should make a similar change to the Hashtable
// code.
39

Bryce McKinlay committed
40 41 42
// NOTE: This implementation has some nasty coding style in order to
// support LinkedHashMap, which extends this.

43 44
/**
 * This class provides a hashtable-backed implementation of the
Bryce McKinlay committed
45 46
 * Map interface.
 * <p>
47
 *
Bryce McKinlay committed
48 49 50 51 52 53
 * It uses a hash-bucket approach; that is, hash collisions are handled
 * by linking the new node off of the pre-existing node (or list of
 * nodes).  In this manner, techniques such as linear probing (which
 * can cause primary clustering) and rehashing (which does not fit very
 * well with Java's method of precomputing hash codes) are avoided.
 * <p>
54
 *
Bryce McKinlay committed
55
 * Under ideal circumstances (no collisions), HashMap offers O(1)
56
 * performance on most operations (<pre>containsValue()</pre> is,
Bryce McKinlay committed
57
 * of course, O(n)).  In the worst case (all keys map to the same
58
 * hash code -- very unlikely), most operations are O(n).
Bryce McKinlay committed
59
 * <p>
60
 *
Bryce McKinlay committed
61
 * HashMap is part of the JDK1.2 Collections API.  It differs from
62 63
 * Hashtable in that it accepts the null key and null values, and it
 * does not support "Enumeration views."
Bryce McKinlay committed
64 65 66 67 68 69 70
 * <p>
 *
 * 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.
71
 *
Bryce McKinlay committed
72 73 74 75 76 77 78 79 80 81 82 83
 * @author Jon Zeppieri
 * @author Jochen Hoenicke
 * @author Bryce McKinlay
 * @author Eric Blake <ebb9@email.byu.edu>
 * @see Object#hashCode()
 * @see Collection
 * @see Map
 * @see TreeMap
 * @see LinkedHashMap
 * @see IdentityHashMap
 * @see Hashtable
 * @since 1.2
84
 */
85 86
public class HashMap extends AbstractMap
  implements Map, Cloneable, Serializable
87
{
Bryce McKinlay committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  /**
   * Default number of buckets. This is the value the JDK 1.3 uses. Some
   * early documentation specified this value as 101. That is incorrect.
   */
  static final int DEFAULT_CAPACITY = 11;

  /**
   * The default load factor; this is explicitly specified by the spec.
   */
  static final float DEFAULT_LOAD_FACTOR = 0.75f;

  /** "enum" of iterator types. */
  static final int KEYS = 0,
                   VALUES = 1,
                   ENTRIES = 2;
103

Bryce McKinlay committed
104 105 106
  /**
   * Compatible with JDK 1.2.
   */
107 108
  private static final long serialVersionUID = 362498820763181265L;

Bryce McKinlay committed
109 110
  /**
   * The rounded product of the capacity and the load factor; when the number
111 112 113 114 115
   * of elements exceeds the threshold, the HashMap calls <pre>rehash()</pre>.
   * @serial
   */
  int threshold;

Bryce McKinlay committed
116 117
  /**
   * Load factor of this HashMap:  used in computing the threshold.
118 119
   * @serial
   */
Bryce McKinlay committed
120
  final float loadFactor;
121

Bryce McKinlay committed
122 123
  /**
   * Array containing the actual key-value mappings.
124
   */
Bryce McKinlay committed
125
  transient HashEntry[] buckets;
126

Bryce McKinlay committed
127 128
  /**
   * Counts the number of modifications this HashMap has undergone, used
129 130 131 132
   * by Iterators to know when to throw ConcurrentModificationExceptions.
   */
  transient int modCount;

Bryce McKinlay committed
133 134 135
  /**
   * The size of this HashMap:  denotes the number of key-value pairs.
   */
136 137 138 139
  transient int size;

  /**
   * Class to represent an entry in the hash table. Holds a single key-value
Bryce McKinlay committed
140 141
   * pair.  This is extended again in LinkedHashMap.  See {@link clone()}
   * for why this must be Cloneable.
142
   */
Bryce McKinlay committed
143
  static class HashEntry extends BasicMapEntry implements Cloneable
144
  {
Bryce McKinlay committed
145 146 147 148 149 150 151 152 153
    /** The next entry in the linked list. */
    HashEntry next;

    /**
     * Simple constructor.
     * @param key the key
     * @param value the value
     */
    HashEntry(Object key, Object value)
154
    {
155
      super(key, value);
156
    }
Bryce McKinlay committed
157 158 159 160 161 162 163 164 165 166

    /**
     * Called when this entry is removed from the map. This version simply
     * returns the value, but in LinkedHashMap, it must also do bookkeeping.
     * @return the value of this key as it is removed.
     */
    Object cleanup()
    {
      return value;
    }
167 168 169
  }

  /**
Bryce McKinlay committed
170
   * Construct a new HashMap with the default capacity (11) and the default
171 172 173 174 175 176 177 178
   * load factor (0.75).
   */
  public HashMap()
  {
    this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
  }

  /**
Bryce McKinlay committed
179 180 181
   * Construct a new HashMap from the given Map, with initial capacity
   * the greater of the size of <code>m</code> or the default of 11.
   * <p>
182
   *
Bryce McKinlay committed
183 184 185 186 187 188
   * Every element in Map m will be put into this new HashMap.
   *
   * @param m a Map whose key / value pairs will be put into
   *          the new HashMap.  <b>NOTE: key / value pairs
   *          are not cloned in this constructor.</b>
   * @throws NullPointerException if m is null
189 190 191
   */
  public HashMap(Map m)
  {
Bryce McKinlay committed
192 193
    this(Math.max(m.size() * 2, DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR);
    putAllInternal(m);
194 195 196
  }

  /**
Bryce McKinlay committed
197 198
   * Construct a new HashMap with a specific inital capacity and
   * default load factor of 0.75.
199
   *
Bryce McKinlay committed
200 201
   * @param initialCapacity the initial capacity of this HashMap (>=0)
   * @throws IllegalArgumentException if (initialCapacity < 0)
202
   */
Bryce McKinlay committed
203
  public HashMap(int initialCapacity)
204 205 206 207 208
  {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
  }

  /**
Bryce McKinlay committed
209
   * Construct a new HashMap with a specific inital capacity and load factor.
210
   *
Bryce McKinlay committed
211 212 213 214
   * @param initialCapacity the initial capacity (>=0)
   * @param loadFactor the load factor (>0, not NaN)
   * @throws IllegalArgumentException if (initialCapacity < 0) ||
   *                                     ! (loadFactor > 0.0)
215 216 217
   */
  public HashMap(int initialCapacity, float loadFactor)
  {
218
    if (initialCapacity < 0)
Bryce McKinlay committed
219 220 221 222
      throw new IllegalArgumentException("Illegal Capacity: "
                                         + initialCapacity);
    if (! (loadFactor > 0)) // check for NaN too
      throw new IllegalArgumentException("Illegal Load: " + loadFactor);
223 224 225

    if (initialCapacity == 0)
      initialCapacity = 1;
Bryce McKinlay committed
226
    buckets = new HashEntry[initialCapacity];
227
    this.loadFactor = loadFactor;
Bryce McKinlay committed
228
    threshold = (int) (initialCapacity * loadFactor);
229 230
  }

Bryce McKinlay committed
231 232 233 234
  /**
   * Returns the number of kay-value mappings currently in this Map
   * @return the size
   */
235 236 237 238 239
  public int size()
  {
    return size;
  }

Bryce McKinlay committed
240 241 242 243
  /**
   * Returns true if there are no key-value mappings currently in this Map
   * @return <code>size() == 0</code>
   */
244 245 246 247 248 249
  public boolean isEmpty()
  {
    return size == 0;
  }

  /**
Bryce McKinlay committed
250
   * Returns true if this HashMap contains a value <pre>o</pre>, such that
251 252
   * <pre>o.equals(value)</pre>.
   *
Bryce McKinlay committed
253 254
   * @param value the value to search for in this HashMap
   * @return true if at least one key maps to the value
255 256 257
   */
  public boolean containsValue(Object value)
  {
Bryce McKinlay committed
258
    for (int i = buckets.length - 1; i >= 0; i--)
259
      {
Bryce McKinlay committed
260 261 262 263 264 265 266
        HashEntry e = buckets[i];
        while (e != null)
          {
            if (value == null ? e.value == null : value.equals(e.value))
              return true;
            e = e.next;
          }
267 268 269 270
      }
    return false;
  }

Bryce McKinlay committed
271 272 273
  /**
   * Returns true if the supplied object <pre>equals()</pre> a key
   * in this HashMap.
274
   *
Bryce McKinlay committed
275 276 277
   * @param key the key to search for in this HashMap
   * @return true if the key is in the table
   * @see #containsValue(Object)
278 279 280 281
   */
  public boolean containsKey(Object key)
  {
    int idx = hash(key);
Bryce McKinlay committed
282
    HashEntry e = buckets[idx];
283 284 285
    while (e != null)
      {
        if (key == null ? e.key == null : key.equals(e.key))
Bryce McKinlay committed
286 287
          return true;
        e = e.next;
288 289 290 291 292
      }
    return false;
  }

  /**
Bryce McKinlay committed
293 294 295 296
   * Return the value in this HashMap associated with the supplied key,
   * or <pre>null</pre> if the key maps to nothing.  NOTE: Since the value
   * could also be null, you must use containsKey to see if this key
   * actually maps to something.
297
   *
Bryce McKinlay committed
298 299 300 301
   * @param key the key for which to fetch an associated value
   * @return what the key maps to, if present
   * @see #put(Object, Object)
   * @see #containsKey(Object)
302 303 304 305
   */
  public Object get(Object key)
  {
    int idx = hash(key);
Bryce McKinlay committed
306
    HashEntry e = buckets[idx];
307 308 309
    while (e != null)
      {
        if (key == null ? e.key == null : key.equals(e.key))
Bryce McKinlay committed
310 311
          return e.value;
        e = e.next;
312 313 314 315 316
      }
    return null;
  }

  /**
Bryce McKinlay committed
317 318 319 320 321
   * Puts the supplied value into the Map, mapped by the supplied key.
   * The value may be retrieved by any object which <code>equals()</code>
   * this key. NOTE: Since the prior value could also be null, you must
   * first use containsKey if you want to see if you are replacing the
   * key's mapping.
322
   *
Bryce McKinlay committed
323 324 325 326 327
   * @param key the key used to locate the value
   * @param value the value to be stored in the HashMap
   * @return the prior mapping of the key, or null if there was none
   * @see #get(Object)
   * @see Object#equals(Object)
328 329 330 331 332
   */
  public Object put(Object key, Object value)
  {
    modCount++;
    int idx = hash(key);
Bryce McKinlay committed
333 334
    HashEntry e = buckets[idx];

335 336 337
    while (e != null)
      {
        if (key == null ? e.key == null : key.equals(e.key))
Bryce McKinlay committed
338 339 340 341
          // Must use this method for necessary bookkeeping in LinkedHashMap.
          return e.setValue(value);
        else
          e = e.next;
342
      }
Bryce McKinlay committed
343

344 345 346
    // At this point, we know we need to add a new entry.
    if (++size > threshold)
      {
Bryce McKinlay committed
347 348 349
        rehash();
        // Need a new hash value to suit the bigger table.
        idx = hash(key);
350 351
      }

Bryce McKinlay committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    // LinkedHashMap cannot override put(), hence this call.
    addEntry(key, value, idx, true);
    return null;
  }

  /**
   * Helper method for put, that creates and adds a new Entry.  This is
   * overridden in LinkedHashMap for bookkeeping purposes.
   *
   * @param key the key of the new Entry
   * @param value the value
   * @param idx the index in buckets where the new Entry belongs
   * @param callRemove Whether to call the removeEldestEntry method.
   * @see #put(Object, Object)
   */
  void addEntry(Object key, Object value, int idx, boolean callRemove)
  {
    HashEntry e = new HashEntry(key, value);

371 372
    e.next = buckets[idx];
    buckets[idx] = e;
373 374 375
  }

  /**
Bryce McKinlay committed
376 377 378 379 380
   * Removes from the HashMap and returns the value which is mapped by the
   * supplied key. If the key maps to nothing, then the HashMap remains
   * unchanged, and <pre>null</pre> is returned. NOTE: Since the value
   * could also be null, you must use containsKey to see if you are
   * actually removing a mapping.
381
   *
Bryce McKinlay committed
382 383
   * @param key the key used to locate the value to remove
   * @return whatever the key mapped to, if present
384 385 386 387 388
   */
  public Object remove(Object key)
  {
    modCount++;
    int idx = hash(key);
Bryce McKinlay committed
389 390
    HashEntry e = buckets[idx];
    HashEntry last = null;
391 392 393 394

    while (e != null)
      {
        if (key == null ? e.key == null : key.equals(e.key))
Bryce McKinlay committed
395 396 397 398 399 400 401 402 403 404 405
          {
            if (last == null)
              buckets[idx] = e.next;
            else
              last.next = e.next;
            size--;
            // Method call necessary for LinkedHashMap to work correctly.
            return e.cleanup();
          }
        last = e;
        e = e.next;
406 407 408 409
      }
    return null;
  }

Bryce McKinlay committed
410 411 412 413 414 415 416
  /**
   * Copies all elements of the given map into this hashtable.  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
   */
417 418 419
  public void putAll(Map m)
  {
    Iterator itr = m.entrySet().iterator();
Bryce McKinlay committed
420 421

    for (int msize = m.size(); msize > 0; msize--)
422 423
      {
        Map.Entry e = (Map.Entry) itr.next();
Bryce McKinlay committed
424 425 426 427 428 429 430 431
        // Optimize in case the Entry is one of our own.
        if (e instanceof BasicMapEntry)
          {
            BasicMapEntry entry = (BasicMapEntry) e;
            put(entry.key, entry.value);
          }
        else
          {
432
            put(e.getKey(), e.getValue());
Bryce McKinlay committed
433
          }
434 435 436
      }
  }
  
Bryce McKinlay committed
437 438 439
  /**
   * Clears the Map so it has no keys. This is O(1).
   */
440 441 442
  public void clear()
  {
    modCount++;
Bryce McKinlay committed
443
    Arrays.fill(buckets, null);
444 445 446
    size = 0;
  }

Bryce McKinlay committed
447 448 449 450 451
  /**
   * Returns a shallow clone of this HashMap. The Map itself is cloned,
   * but its contents are not.  This is O(n).
   *
   * @return the clone
452 453 454 455 456 457 458 459 460 461
   */
  public Object clone()
  {
    HashMap copy = null;
    try
      {
        copy = (HashMap) super.clone();
      }
    catch (CloneNotSupportedException x)
      {
Bryce McKinlay committed
462
        // This is impossible.
463
      }
Bryce McKinlay committed
464 465
    copy.buckets = new HashEntry[buckets.length];
    copy.putAllInternal(this);
466 467 468
    return copy;
  }

Bryce McKinlay committed
469 470 471 472 473 474 475 476 477
  /**
   * Returns a "set view" of this HashMap's keys. The set is backed by the
   * HashMap, so changes in one show up in the other.  The set supports
   * element removal, but not element addition.
   *
   * @return a set view of the keys
   * @see #values()
   * @see #entrySet()
   */
478 479
  public Set keySet()
  {
Bryce McKinlay committed
480 481
    // Create an AbstractSet with custom implementations of those methods that
    // can be overridden easily and efficiently.
482
    return new AbstractSet()
483
    {
484 485 486 487
      public int size()
      {
        return size;
      }
Bryce McKinlay committed
488

489 490
      public Iterator iterator()
      {
Bryce McKinlay committed
491 492
        // Cannot create the iterator directly, because of LinkedHashMap.
        return HashMap.this.iterator(KEYS);
493
      }
Bryce McKinlay committed
494

495 496 497 498 499 500 501 502 503
      public void clear()
      {
        HashMap.this.clear();
      }

      public boolean contains(Object o)
      {
        return HashMap.this.containsKey(o);
      }
Bryce McKinlay committed
504

505 506 507
      public boolean remove(Object o)
      {
        // Test against the size of the HashMap to determine if anything
508
        // really got removed. This is necessary because the return value of
Bryce McKinlay committed
509
        // HashMap.remove() is ambiguous in the null case.
510 511
        int oldsize = size;
        HashMap.this.remove(o);
Bryce McKinlay committed
512
        return (oldsize != size);
513 514 515
      }
    };
  }
Bryce McKinlay committed
516 517 518 519 520 521 522 523 524 525 526

  /**
   * Returns a "collection view" (or "bag view") of this HashMap's values.
   * The collection is backed by the HashMap, so changes in one show up
   * in the other.  The collection supports element removal, but not element
   * addition.
   *
   * @return a bag view of the values
   * @see #keySet()
   * @see #entrySet()
   */
527 528 529 530 531
  public Collection values()
  {
    // We don't bother overriding many of the optional methods, as doing so
    // wouldn't provide any significant performance advantage.
    return new AbstractCollection()
532
    {
533 534 535 536
      public int size()
      {
        return size;
      }
Bryce McKinlay committed
537

538 539
      public Iterator iterator()
      {
Bryce McKinlay committed
540 541
        // Cannot create the iterator directly, because of LinkedHashMap.
        return HashMap.this.iterator(VALUES);
542
      }
Bryce McKinlay committed
543

544 545 546 547 548 549 550
      public void clear()
      {
        HashMap.this.clear();
      }
    };
  }

Bryce McKinlay committed
551 552 553 554 555 556 557 558 559 560 561 562 563 564
  /**
   * Returns a "set view" of this HashMap's entries. The set is backed by
   * the HashMap, so changes in one show up in the other.  The set supports
   * element removal, but not element addition.
   * <p>
   *
   * Note that the iterators for all three views, from keySet(), entrySet(),
   * and values(), traverse the HashMap in the same sequence.
   *
   * @return a set view of the entries
   * @see #keySet()
   * @see #values()
   * @see Map.Entry
   */
565 566
  public Set entrySet()
  {
Bryce McKinlay committed
567 568
    // Create an AbstractSet with custom implementations of those methods that
    // can be overridden easily and efficiently.
569
    return new AbstractSet()
570
    {
571 572 573 574
      public int size()
      {
        return size;
      }
Bryce McKinlay committed
575

576 577
      public Iterator iterator()
      {
Bryce McKinlay committed
578 579
        // Cannot create the iterator directly, because of LinkedHashMap.
        return HashMap.this.iterator(ENTRIES);
580
      }
Bryce McKinlay committed
581

582 583 584 585 586 587 588
      public void clear()
      {
        HashMap.this.clear();
      }

      public boolean contains(Object o)
      {
Bryce McKinlay committed
589
        return getEntry(o) != null;
590
      }
Bryce McKinlay committed
591

592 593
      public boolean remove(Object o)
      {
Bryce McKinlay committed
594 595 596 597 598 599 600
        HashEntry e = getEntry(o);
        if (e != null)
          {
            HashMap.this.remove(e.key);
            return true;
          }
        return false;
601 602 603
      }
    };
  }
Bryce McKinlay committed
604 605 606 607 608 609 610 611

  /** Helper method that returns an index in the buckets array for `key;
   * based on its hashCode().
   *
   * @param key the key
   * @return the bucket number
   */
  int hash(Object key)
612
  {
Bryce McKinlay committed
613
    return (key == null) ? 0 : Math.abs(key.hashCode() % buckets.length);
614 615
  }

Bryce McKinlay committed
616 617 618 619 620 621 622 623 624
  /**
   * Helper method for entrySet(), which matches both key and value
   * simultaneously.
   *
   * @param o the entry to match
   * @return the matching entry, if found, or null
   * @see #entrySet()
   */
  private HashEntry getEntry(Object o)
625
  {
Bryce McKinlay committed
626 627 628
    if (!(o instanceof Map.Entry))
      return null;
    Map.Entry me = (Map.Entry) o;
629
    int idx = hash(me.getKey());
Bryce McKinlay committed
630
    HashEntry e = buckets[idx];
631 632 633
    while (e != null)
      {
        if (e.equals(me))
Bryce McKinlay committed
634 635
          return e;
        e = e.next;
636 637 638
      }
    return null;
  }
Bryce McKinlay committed
639 640 641 642 643

  /**
   * Increases the size of the HashMap and rehashes all keys to new array
   * indices; this is called when the addition of a new value would cause
   * size() > threshold. Note that the existing Entry objects are reused in
644
   * the new hash table.
Bryce McKinlay committed
645 646 647 648
   * <p>
   *
   * This is not specified, but the new size is twice the current size plus
   * one; this number is not always prime, unfortunately.
649 650 651
   */
  private void rehash()
  {
Bryce McKinlay committed
652 653
    HashEntry[] oldBuckets = buckets;

654 655
    int newcapacity = (buckets.length * 2) + 1;
    threshold = (int) (newcapacity * loadFactor);
Bryce McKinlay committed
656 657 658
    buckets = new HashEntry[newcapacity];

    for (int i = oldBuckets.length - 1; i >= 0; i--)
659
      {
Bryce McKinlay committed
660
        HashEntry e = oldBuckets[i];
661
        while (e != null)
Bryce McKinlay committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
          {
            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;
          }
      }
  }

  /**
   * Generates a parameterized iterator.  Must be overrideable, since
   * LinkedHashMap iterates in a different order.
   * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
   * @return the appropriate iterator
   */
  Iterator iterator(int type)
  {
    return new HashIterator(type);
  }

  /**
   * 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.
   */
  void putAllInternal(Map m)
  {
    Iterator itr = m.entrySet().iterator();

    for (int msize = m.size(); msize > 0; msize--)
      {
	Map.Entry e = (Map.Entry) itr.next();
	Object key = e.getKey();
	int idx = hash(key);
	addEntry(key, e.getValue(), idx, false);
710 711 712 713 714
      }
  }

  /**
   * Serializes this object to the given stream.
Bryce McKinlay committed
715 716 717 718 719 720 721
   *
   * @param s the stream to write to
   * @throws IOException if the underlying stream fails
   * @serialData the <i>capacity</i>(int) that is the length of the
   *             bucket array, the <i>size</i>(int) of the hash map
   *             are emitted first.  They are followed by size entries,
   *             each consisting of a key (Object) and a value (Object).
722 723 724
   */
  private void writeObject(ObjectOutputStream s) throws IOException
  {
Bryce McKinlay committed
725
    // Write the threshold and loadFactor fields.
726 727 728 729
    s.defaultWriteObject();

    s.writeInt(buckets.length);
    s.writeInt(size);
Bryce McKinlay committed
730 731
    // Avoid creating a wasted Set by creating the iterator directly.
    Iterator it = iterator(ENTRIES);
732 733
    while (it.hasNext())
      {
Bryce McKinlay committed
734 735 736
        HashEntry entry = (HashEntry) it.next();
        s.writeObject(entry.key);
        s.writeObject(entry.value);
737 738 739 740 741
      }
  }

  /**
   * Deserializes this object from the given stream.
Bryce McKinlay committed
742 743 744 745 746 747 748 749
   *
   * @param s the stream to read from
   * @throws ClassNotFoundException if the underlying stream fails
   * @throws IOException if the underlying stream fails
   * @serialData the <i>capacity</i>(int) that is the length of the
   *             bucket array, the <i>size</i>(int) of the hash map
   *             are emitted first.  They are followed by size entries,
   *             each consisting of a key (Object) and a value (Object).
750 751 752 753
   */
  private void readObject(ObjectInputStream s)
    throws IOException, ClassNotFoundException
  {
Bryce McKinlay committed
754
    // Read the threshold and loadFactor fields.
755 756
    s.defaultReadObject();

Bryce McKinlay committed
757 758
    // Read and use capacity.
    buckets = new HashEntry[s.readInt()];
759
    int len = s.readInt();
Bryce McKinlay committed
760 761 762
    // Already happens automatically.
    // size = 0;
    // modCount = 0;
763

Bryce McKinlay committed
764 765 766
    // Read and use key/value pairs.
    for ( ; len > 0; len--)
      put(s.readObject(), s.readObject());
767 768 769
  }

  /**
770 771 772
   * Iterate over HashMap's entries.
   * This implementation is parameterized to give a sequential view of
   * keys, values, or entries.
773
   *
Bryce McKinlay committed
774
   * @author Jon Zeppieri
775 776 777
   */
  class HashIterator implements Iterator
  {
Bryce McKinlay committed
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
    /**
     * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
     * or {@link #ENTRIES}.
     */
    final int type;
    /**
     * The number of modifications to the backing HashMap 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}
     */
804
    HashIterator(int type)
805
    {
806
      this.type = type;
807 808
    }

Bryce McKinlay committed
809 810 811 812 813
    /**
     * Returns true if the Iterator has more elements.
     * @return true if there are more elements
     * @throws ConcurrentModificationException if the HashMap was modified
     */
814
    public boolean hasNext()
815
    {
Bryce McKinlay committed
816 817 818
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
      return count > 0;
819 820
    }

Bryce McKinlay committed
821 822 823 824 825 826
    /**
     * Returns the next element in the Iterator's sequential view.
     * @return the next element
     * @throws ConcurrentModificationException if the HashMap was modified
     * @throws NoSuchElementException if there is none
     */
827
    public Object next()
828
    {
Bryce McKinlay committed
829 830 831
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
      if (count == 0)
832
        throw new NoSuchElementException();
Bryce McKinlay committed
833 834
      count--;
      HashEntry e = next;
835 836

      while (e == null)
Bryce McKinlay committed
837
        e = buckets[--idx];
838 839 840 841 842 843 844 845

      next = e.next;
      last = e;
      if (type == VALUES)
        return e.value;
      else if (type == KEYS)
        return e.key;
      return e;
846 847
    }

Bryce McKinlay committed
848 849 850 851 852
    /**
     * Removes from the backing HashMap the last element which was fetched
     * with the <pre>next()</pre> method.
     * @throws ConcurrentModificationException if the HashMap was modified
     * @throws IllegalStateException if called when there is no last element
853
     */
854
    public void remove()
855
    {
Bryce McKinlay committed
856 857
      if (knownMod != modCount)
        throw new ConcurrentModificationException();
858
      if (last == null)
Bryce McKinlay committed
859 860 861 862 863
        throw new IllegalStateException();

      HashMap.this.remove(last.key);
      knownMod++;
      last = null;
864
    }
865
  }
866
}