/[classpath]/classpath/java/util/Hashtable.java
ViewVC logotype

Diff of /classpath/java/util/Hashtable.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.16 by ericb, Tue Sep 18 03:25:11 2001 UTC revision 1.17 by ericb, Thu Sep 20 23:38:12 2001 UTC
# Line 8  GNU Classpath is free software; you can Line 8  GNU Classpath is free software; you can
8  it under the terms of the GNU General Public License as published by  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation; either version 2, or (at your option)  the Free Software Foundation; either version 2, or (at your option)
10  any later version.  any later version.
11    
12  GNU Classpath is distributed in the hope that it will be useful, but  GNU Classpath is distributed in the hope that it will be useful, but
13  WITHOUT ANY WARRANTY; without even the implied warranty of  WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Line 38  import java.io.ObjectOutputStream; Line 38  import java.io.ObjectOutputStream;
38    
39  /**  /**
40   * A class which implements a hashtable data structure.   * A class which implements a hashtable data structure.
41     * <p>
42   *   *
43   * This implementation of Hashtable uses a hash-bucket approach. That is:   * This implementation of Hashtable uses a hash-bucket approach. That is:
44   * linear probing and rehashing is avoided; instead, each hashed value maps   * linear probing and rehashing is avoided; instead, each hashed value maps
45   * to a simple linked-list which, in the best case, only has one node.   * to a simple linked-list which, in the best case, only has one node.
46   * Assuming a large enough table, low enough load factor, and / or well   * Assuming a large enough table, low enough load factor, and / or well
47   * implemented hashCode() methods, Hashtable should provide O(1)   * implemented hashCode() methods, Hashtable should provide O(1)
48   * insertion, deletion, and searching of keys.  Hashtable is O(n) in   * insertion, deletion, and searching of keys.  Hashtable is O(n) in
49   * the worst case for all of these (if all keys hash to the same bucket).   * the worst case for all of these (if all keys hash to the same bucket).
50   * <p>   * <p>
51   *   *
52   * This is a JDK-1.2 compliant implementation of Hashtable.  As such, it   * This is a JDK-1.2 compliant implementation of Hashtable.  As such, it
53   * belongs, partially, to the Collections framework (in that it implements   * belongs, partially, to the Collections framework (in that it implements
54   * Map).  For backwards compatibility, it inherits from the obsolete and   * Map).  For backwards compatibility, it inherits from the obsolete and
55   * utterly useless Dictionary class.   * utterly useless Dictionary class.
56   * <p>   * <p>
57   *   *
# Line 66  import java.io.ObjectOutputStream; Line 67  import java.io.ObjectOutputStream;
67   * all accesses are synchronized: in a single thread environment, this is   * all accesses are synchronized: in a single thread environment, this is
68   * expensive, but in a multi-thread environment, this saves you the effort   * expensive, but in a multi-thread environment, this saves you the effort
69   * of extra synchronization.   * of extra synchronization.
70     * <p>
71     *
72     * The iterators are <i>fail-fast</i>, meaning that any structural
73     * modification, except for <code>remove()</code> called on the iterator
74     * itself, cause the iterator to throw a
75     * <code>ConcurrentModificationException</code> rather than exhibit
76     * non-deterministic behavior.
77   *   *
78   * @author Jon Zeppieri   * @author Jon Zeppieri
79   * @author Warren Levy   * @author Warren Levy
# Line 77  import java.io.ObjectOutputStream; Line 85  import java.io.ObjectOutputStream;
85   * @see LinkedHashMap   * @see LinkedHashMap
86   * @since 1.0   * @since 1.0
87   */   */
88  public class Hashtable extends Dictionary  public class Hashtable extends Dictionary
89    implements Map, Cloneable, Serializable    implements Map, Cloneable, Serializable
90  {  {
91    /** Default number of buckets. This is the value the JDK 1.3 uses. Some    /** Default number of buckets. This is the value the JDK 1.3 uses. Some
92      * early documentation specified this value as 101. That is incorrect.     * early documentation specified this value as 101. That is incorrect.
93      */     */
94    private static final int DEFAULT_CAPACITY = 11;    private static final int DEFAULT_CAPACITY = 11;
95    /** The default load factor; this is explicitly specified by the spec. */  
96      /**
97       * The default load factor; this is explicitly specified by the spec.
98       */
99    private static final float DEFAULT_LOAD_FACTOR = 0.75f;    private static final float DEFAULT_LOAD_FACTOR = 0.75f;
100    
101    /**    /**
# Line 92  public class Hashtable extends Dictionar Line 103  public class Hashtable extends Dictionar
103     */     */
104    private static final long serialVersionUID = 1421746759512286392L;    private static final long serialVersionUID = 1421746759512286392L;
105    
106    /**    /**
107     * The rounded product of the capacity and the load factor; when the number     * The rounded product of the capacity and the load factor; when the number
108     * of elements exceeds the threshold, the Hashtable calls     * of elements exceeds the threshold, the Hashtable calls
109     * <pre>rehash()</pre>.     * <pre>rehash()</pre>.
110     * @serial     * @serial
111     */     */
112    int threshold;    int threshold;
113    
114    /** Load factor of this Hashtable:  used in computing the threshold.    /**
115       * Load factor of this Hashtable:  used in computing the threshold.
116     * @serial     * @serial
117     */     */
118    float loadFactor;    final float loadFactor;
119    
120    /**    /**
121     * Array containing the actual key-value mappings     * Array containing the actual key-value mappings.
122     */     */
123    transient HashEntry[] buckets;    transient HashEntry[] buckets;
124    
125    /**    /**
126     * Counts the number of modifications this Hashtable has undergone, used     * Counts the number of modifications this Hashtable has undergone, used
127     * by Iterators to know when to throw ConcurrentModificationExceptions.     * by Iterators to know when to throw ConcurrentModificationExceptions.
128     */     */
129    transient int modCount;    transient int modCount;
130    
131    /** The size of this Hashtable:  denotes the number of key-value pairs */    /**
132       * The size of this Hashtable:  denotes the number of key-value pairs.
133       */
134    transient int size;    transient int size;
135    
136    /**    /**
137     * Class to represent an entry in the hash table. Holds a single key-value     * Class to represent an entry in the hash table. Holds a single key-value
138     * pair. A Hashtable Entry is identical to a HashMap Entry, except that     * pair. A Hashtable Entry is identical to a HashMap Entry, except that
139     * `null' is not allowed for keys and values.     * `null' is not allowed for keys and values.
140     */     */
141    static class HashEntry extends BasicMapEntry    static class HashEntry extends BasicMapEntry
142    {    {
143      /** The next entry in the linked list */      /** The next entry in the linked list. */
144      HashEntry next;      HashEntry next;
145    
146      /**      /**
# Line 147  public class Hashtable extends Dictionar Line 161  public class Hashtable extends Dictionar
161       */       */
162      public final Object setValue(Object newVal)      public final Object setValue(Object newVal)
163      {      {
164        // Throw a NullPointerException with minimal bytecode        if (newVal == null)
165        newVal.getClass();          throw new NullPointerException();
166        return super.setValue(newVal);        return super.setValue(newVal);
167      }      }
168    }    }
# Line 164  public class Hashtable extends Dictionar Line 178  public class Hashtable extends Dictionar
178    
179    /**    /**
180     * Construct a new Hashtable from the given Map, with initial capacity     * Construct a new Hashtable from the given Map, with initial capacity
181     * the greater of the size of m or the default of 11.     * the greater of the size of <code>m</code> or the default of 11.
182     * <p>     * <p>
183     *     *
184     * Every element in Map m will be put into this new Hashtable     * Every element in Map m will be put into this new Hashtable.
185     *     *
186     * @param m a Map whose key / value pairs will be put into     * @param m a Map whose key / value pairs will be put into
187     *          the new Hashtable.  <b>NOTE: key / value pairs     *          the new Hashtable.  <b>NOTE: key / value pairs
188     *          are not cloned in this constructor</b>     *          are not cloned in this constructor.</b>
189     * @throws NullPointerException if m is null, or if m contains a mapping     * @throws NullPointerException if m is null, or if m contains a mapping
190     *         to or from `null'.     *         to or from `null'.
191     * @since 1.2     * @since 1.2
192     */     */
193    public Hashtable(Map m)    public Hashtable(Map m)
194    {    {
195      this(Math.max(m.size() * 2, DEFAULT_CAPACITY));      this(Math.max(m.size() * 2, DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR);
196      putAll(m);      putAll(m);
197    }    }
198    
# Line 201  public class Hashtable extends Dictionar Line 215  public class Hashtable extends Dictionar
215     * @param initialCapacity the initial capacity (>=0)     * @param initialCapacity the initial capacity (>=0)
216     * @param loadFactor the load factor (>0, not NaN)     * @param loadFactor the load factor (>0, not NaN)
217     * @throws IllegalArgumentException if (initialCapacity < 0) ||     * @throws IllegalArgumentException if (initialCapacity < 0) ||
218     *                                     ! (initialLoadFactor > 0.0)     *                                     ! (loadFactor > 0.0)
219     */     */
220    public Hashtable(int initialCapacity, float loadFactor)    public Hashtable(int initialCapacity, float loadFactor)
221    {    {
222      if (initialCapacity < 0)      if (initialCapacity < 0)
223        throw new IllegalArgumentException("Illegal Capacity: "        throw new IllegalArgumentException("Illegal Capacity: "
224                                           + initialCapacity);                                           + initialCapacity);
225      if (! (loadFactor > 0)) // check for NaN too      if (! (loadFactor > 0)) // check for NaN too
226        throw new IllegalArgumentException("Illegal Load: " + loadFactor);        throw new IllegalArgumentException("Illegal Load: " + loadFactor);
# Line 215  public class Hashtable extends Dictionar Line 229  public class Hashtable extends Dictionar
229        initialCapacity = 1;        initialCapacity = 1;
230      buckets = new HashEntry[initialCapacity];      buckets = new HashEntry[initialCapacity];
231      this.loadFactor = loadFactor;      this.loadFactor = loadFactor;
232      this.threshold = (int) (initialCapacity * loadFactor);      threshold = (int) (initialCapacity * loadFactor);
233    }    }
234    
235    /**    /**
# Line 276  public class Hashtable extends Dictionar Line 290  public class Hashtable extends Dictionar
290     */     */
291    public synchronized boolean contains(Object value)    public synchronized boolean contains(Object value)
292    {    {
293      // Check if value is null with minimal bytecode, in case      // Check if value is null in case Hashtable is empty.
294      // Hashtable is empty.      if (value == null)
295      value.getClass();        throw new NullPointerException();
296    
297      for (int i = 0; i < buckets.length; i++)      for (int i = buckets.length - 1; i >= 0; i--)
298        {        {
299          HashEntry e = buckets[i];          HashEntry e = buckets[i];
300          while (e != null)          while (e != null)
# Line 310  public class Hashtable extends Dictionar Line 324  public class Hashtable extends Dictionar
324      return contains(value);      return contains(value);
325    }    }
326    
327    /**    /**
328     * Returns true if the supplied object (<pre>equals()</pre>) a key     * Returns true if the supplied object <pre>equals()</pre> a key
329     * in this Hashtable     * in this Hashtable.
330     *     *
331     * @param key the key to search for in this Hashtable     * @param key the key to search for in this Hashtable
332     * @return true if the key is in the table     * @return true if the key is in the table
# Line 334  public class Hashtable extends Dictionar Line 348  public class Hashtable extends Dictionar
348    
349    /**    /**
350     * Return the value in this Hashtable associated with the supplied key,     * Return the value in this Hashtable associated with the supplied key,
351     * or <pre>null</pre> if the key maps to nothing     * or <pre>null</pre> if the key maps to nothing.
352     *     *
353     * @param key the key for which to fetch an associated value     * @param key the key for which to fetch an associated value
354     * @return what the key maps to, if present     * @return what the key maps to, if present
355     * @throws NullPointerException if key is null     * @throws NullPointerException if key is null
356     * @see #put(Object, Object)     * @see #put(Object, Object)
357       * @see #containsKey(Object)
358     */     */
359    public synchronized Object get(Object key)    public synchronized Object get(Object key)
360    {    {
# Line 372  public class Hashtable extends Dictionar Line 387  public class Hashtable extends Dictionar
387      int idx = hash(key);      int idx = hash(key);
388      HashEntry e = buckets[idx];      HashEntry e = buckets[idx];
389    
390      // Check if value is null with minimal bytecode, since      // Check if value is null since it is not permitted.
391      // Hashtable does not accept null values.      if (value == null)
392      value.getClass();        throw new NullPointerException();
393    
394      while (e != null)      while (e != null)
395        {        {
396          if (key.equals(e.key))          if (key.equals(e.key))
397            {            {
398                // Bypass e.setValue, since we already know value is non-null.
399              Object r = e.value;              Object r = e.value;
400              e.value = value;              e.value = value;
401              return r;              return r;
# Line 407  public class Hashtable extends Dictionar Line 423  public class Hashtable extends Dictionar
423    }    }
424    
425    /**    /**
426     * Removes from the table and returns the value which is mapped by the     * Removes from the table and returns the value which is mapped by the
427     * supplied key. If the key maps to nothing, then the table remains     * supplied key. If the key maps to nothing, then the table remains
428     * unchanged, and <pre>null</pre> is returned.     * unchanged, and <pre>null</pre> is returned.
429     *     *
430     * @param key the key used to locate the value to remove     * @param key the key used to locate the value to remove
# Line 449  public class Hashtable extends Dictionar Line 465  public class Hashtable extends Dictionar
465     */     */
466    public synchronized void putAll(Map m)    public synchronized void putAll(Map m)
467    {    {
     int msize = m.size();  
468      Iterator itr = m.entrySet().iterator();      Iterator itr = m.entrySet().iterator();
469    
470      for (int i = 0; i < msize; i++)      for (int msize = m.size(); msize > 0; msize--)
471        {        {
472          Entry e = (Entry) itr.next();          Map.Entry e = (Map.Entry) itr.next();
473          // Optimize in case the Entry is one of our own.          // Optimize in case the Entry is one of our own.
474          if (e instanceof BasicMapEntry)          if (e instanceof BasicMapEntry)
475            {            {
# Line 474  public class Hashtable extends Dictionar Line 489  public class Hashtable extends Dictionar
489    public synchronized void clear()    public synchronized void clear()
490    {    {
491      modCount++;      modCount++;
492      buckets = new HashEntry[buckets.length];      Arrays.fill(buckets, null);
493      size = 0;      size = 0;
494    }    }
495    
496    /**    /**
497     * Returns a shallow clone of this Hashtable. The Map itself is cloned,     * Returns a shallow clone of this Hashtable. The Map itself is cloned,
498     * but its contents are not.  This is O(n).     * but its contents are not.  This is O(n).
499     *     *
500     * @return the clone     * @return the clone
# Line 493  public class Hashtable extends Dictionar Line 508  public class Hashtable extends Dictionar
508        }        }
509      catch (CloneNotSupportedException x)      catch (CloneNotSupportedException x)
510        {        {
511            // This is impossible.
512        }        }
513      copy.buckets = new HashEntry[buckets.length];      copy.buckets = new HashEntry[buckets.length];
514    
515      for (int i = 0; i < buckets.length; i++)      for (int i = buckets.length - 1; i >= 0; i--)
516        {        {
517          HashEntry e = buckets[i];          HashEntry e = buckets[i];
518          HashEntry last = null;          HashEntry last = null;
# Line 538  public class Hashtable extends Dictionar Line 554  public class Hashtable extends Dictionar
554      // unsynchronized HashIterator instead.      // unsynchronized HashIterator instead.
555      Iterator entries = new HashIterator(HashIterator.ENTRIES);      Iterator entries = new HashIterator(HashIterator.ENTRIES);
556      StringBuffer r = new StringBuffer("{");      StringBuffer r = new StringBuffer("{");
557      for (int pos = 0; pos < size; pos++)      for (int pos = size; pos > 0; pos--)
558        {        {
559          r.append(entries.next());          r.append(entries.next());
560          if (pos < size - 1)          if (pos == 1)
561            r.append(", ");            r.append(", ");
562        }        }
563      r.append("}");      r.append("}");
# Line 563  public class Hashtable extends Dictionar Line 579  public class Hashtable extends Dictionar
579     */     */
580    public Set keySet()    public Set keySet()
581    {    {
582      // Create a synchronized AbstractSet with custom implementations of those      // Create a synchronized AbstractSet with custom implementations of those
583      // methods that can be overriden easily and efficiently.      // methods that can be overridden easily and efficiently.
584      Set r = new AbstractSet()      Set r = new AbstractSet()
585      {      {
586        public int size()        public int size()
# Line 600  public class Hashtable extends Dictionar Line 616  public class Hashtable extends Dictionar
616    
617    
618    /**    /**
619     * Returns a "collection view" (or "bag view") of this Hashtable's values.     * Returns a "collection view" (or "bag view") of this Hashtable's values.
620     * The collection is backed by the hashtable, so changes in one show up     * The collection is backed by the hashtable, so changes in one show up
621     * in the other.  The collection supports element removal, but not element     * in the other.  The collection supports element removal, but not element
622     * addition.  The collection is properly synchronized on the original     * addition.  The collection is properly synchronized on the original
# Line 654  public class Hashtable extends Dictionar Line 670  public class Hashtable extends Dictionar
670     * {@link NullPointerException} if the Map.Entry passed to     * {@link NullPointerException} if the Map.Entry passed to
671     * <code>contains</code>, <code>remove</code>, or related methods returns     * <code>contains</code>, <code>remove</code>, or related methods returns
672     * null for <code>getKey</code>, but not if the Map.Entry is null or     * null for <code>getKey</code>, but not if the Map.Entry is null or
673     * returns null for <code>getValue</code>.     * returns null for <code>getValue</code>.
674     * <p>     * <p>
675     *     *
676     * Note that the iterators for all three views, from keySet(), entrySet(),     * Note that the iterators for all three views, from keySet(), entrySet(),
# Line 668  public class Hashtable extends Dictionar Line 684  public class Hashtable extends Dictionar
684     */     */
685    public Set entrySet()    public Set entrySet()
686    {    {
687      // Create an AbstractSet with custom implementations of those methods that      // Create an AbstractSet with custom implementations of those methods that
688      // can be overriden easily and efficiently.      // can be overridden easily and efficiently.
689      Set r = new AbstractSet()      Set r = new AbstractSet()
690      {      {
691        public int size()        public int size()
# Line 689  public class Hashtable extends Dictionar Line 705  public class Hashtable extends Dictionar
705    
706        public boolean contains(Object o)        public boolean contains(Object o)
707        {        {
708          if (!(o instanceof Entry))          return getEntry(o) != null;
           return false;  
         Entry me = (Entry) o;  
         HashEntry e = getEntry(me);  
         return (e != null);  
709        }        }
710    
711        public boolean remove(Object o)        public boolean remove(Object o)
712        {        {
713          if (!(o instanceof Entry))          HashEntry e = getEntry(o);
           return false;  
         Entry me = (Entry) o;  
         HashEntry e = getEntry(me);  
714          if (e != null)          if (e != null)
715            {            {
716              Hashtable.this.remove(e.key);              Hashtable.this.remove(e.key);
# Line 752  public class Hashtable extends Dictionar Line 761  public class Hashtable extends Dictionar
761      // unsynchronized HashIterator instead.      // unsynchronized HashIterator instead.
762      Iterator itr = new HashIterator(HashIterator.ENTRIES);      Iterator itr = new HashIterator(HashIterator.ENTRIES);
763      int hashcode = 0;      int hashcode = 0;
764      for (int pos = 0; pos < size; pos++)      for (int pos = size; pos > 0; pos--)
765        {        hashcode += itr.next().hashCode();
766          hashcode += itr.next().hashCode();  
       }  
767      return hashcode;      return hashcode;
768    }    }
769    
# Line 776  public class Hashtable extends Dictionar Line 784  public class Hashtable extends Dictionar
784     * Helper method for entrySet(), which matches both key and value     * Helper method for entrySet(), which matches both key and value
785     * simultaneously.     * simultaneously.
786     *     *
787     * @param me the entry to match     * @param o the entry to match
788     * @return the matching entry, if found, or null     * @return the matching entry, if found, or null
789     * @throws NullPointerException if me.getKey() returns null     * @throws NullPointerException if me.getKey() returns null
790     * @see #entrySet()     * @see #entrySet()
791     */     */
792    private HashEntry getEntry(Entry me)    private HashEntry getEntry(Object o)
793    {    {
794      if (me == null)      if (!(o instanceof Map.Entry))
795        return null;        return null;
796        Map.Entry me = (Map.Entry) o;
797      int idx = hash(me.getKey());      int idx = hash(me.getKey());
798      HashEntry e = buckets[idx];      HashEntry e = buckets[idx];
799      while (e != null)      while (e != null)
# Line 796  public class Hashtable extends Dictionar Line 805  public class Hashtable extends Dictionar
805      return null;      return null;
806    }    }
807    
808    /**    /**
809     * Increases the size of the Hashtable and rehashes all keys to new array     * Increases the size of the Hashtable and rehashes all keys to new array
810     * indices; this is called when the addition of a new value would cause     * indices; this is called when the addition of a new value would cause
811     * size() > threshold. Note that the existing Entry objects are reused in     * size() > threshold. Note that the existing Entry objects are reused in
812     * the new hash table.     * the new hash table.
813     * <p>     * <p>
814     *     *
# Line 814  public class Hashtable extends Dictionar Line 823  public class Hashtable extends Dictionar
823      threshold = (int) (newcapacity * loadFactor);      threshold = (int) (newcapacity * loadFactor);
824      buckets = new HashEntry[newcapacity];      buckets = new HashEntry[newcapacity];
825    
826      for (int i = 0; i < oldBuckets.length; i++)      for (int i =oldBuckets.length - 1; i >= 0; i--)
827        {        {
828          HashEntry e = oldBuckets[i];          HashEntry e = oldBuckets[i];
829          while (e != null)          while (e != null)
# Line 887  public class Hashtable extends Dictionar Line 896  public class Hashtable extends Dictionar
896      // Read the threshold and loadFactor fields.      // Read the threshold and loadFactor fields.
897      s.defaultReadObject();      s.defaultReadObject();
898    
899      int capacity = s.readInt();      // Read and use capacity.
900        buckets = new HashEntry[s.readInt()];
901      int len = s.readInt();      int len = s.readInt();
902      size = 0;      // Already happens automatically.
903      modCount = 0;      // size = 0;
904      buckets = new HashEntry[capacity];      // modCount = 0;
905    
906      for (int i = 0; i < len; i++)      // Read and use key/value pairs.
907        {      for ( ; len > 0; len--)
908          Object key = s.readObject();        put(s.readObject(), s.readObject());
         Object value = s.readObject();  
         put(key, value);  
       }  
909    }    }
910    
911    /**    /**
912     * A class which implements the Iterator interface and is used for     * A class which implements the Iterator interface and is used for
913     * iterating over Hashtables.     * iterating over Hashtables.
914     * This implementation is parameterized to give a sequential view of     * This implementation is parameterized to give a sequential view of
915     * keys, values, or entries; it also allows the removal of elements,     * keys, values, or entries; it also allows the removal of elements,
916     * as per the Javasoft spec.  Note that it is not synchronized; this is     * as per the Javasoft spec.  Note that it is not synchronized; this is
917     * a performance enhancer since it is never exposed externally and is     * a performance enhancer since it is never exposed externally and is
918     * only used within synchronized blocks above.     * only used within synchronized blocks above.
# Line 915  public class Hashtable extends Dictionar Line 922  public class Hashtable extends Dictionar
922    class HashIterator implements Iterator    class HashIterator implements Iterator
923    {    {
924      /** "enum" of iterator types. */      /** "enum" of iterator types. */
925      static final int KEYS = 0;      static final int KEYS = 0,
926      /** "enum" of iterator types. */                       VALUES = 1,
927      static final int VALUES = 1;                       ENTRIES = 2;
     /** "enum" of iterator types. */  
     static final int ENTRIES = 2;  
928    
929      /**      /**
930       * The type of this Iterator: {@link KEYS}, {@link VALUES},       * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
931       * or {@link ENTRIES}.       * or {@link #ENTRIES}.
932       */       */
933      int type;      final int type;
934      /**      /**
935       * The number of modifications to the backing Hashtable that we know about.       * The number of modifications to the backing Hashtable that we know about.
936       */       */
937      int knownMod;      int knownMod = modCount;
938      /**      /** The number of elements remaining to be returned by next(). */
939       * The total number of elements returned by next(). Used to determine if      int count = size;
      * there are more elements remaining.  
      */  
     int count;  
940      /** Current index in the physical hash table. */      /** Current index in the physical hash table. */
941      int idx;      int idx = buckets.length;
942      /** The last Entry returned by a next() call. */      /** The last Entry returned by a next() call. */
943      HashEntry last;      HashEntry last;
944      /**      /**
945       * The next entry that should be returned by next(). It is set to something       * The next entry that should be returned by next(). It is set to something
946       * if we're iterating through a bucket that contains multiple linked       * if we're iterating through a bucket that contains multiple linked
947       * entries. It is null if next() needs to find a new bucket.       * entries. It is null if next() needs to find a new bucket.
948       */       */
949      HashEntry next;      HashEntry next;
950    
951      /**      /**
952       * Construct a new HashIterator with the supplied type.       * Construct a new HashIterator with the supplied type.
953       * @param type {@link KEYS}, {@link VALUES}, or {@link ENTRIES}       * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
954       */       */
955      HashIterator(int type)      HashIterator(int type)
956      {      {
957        this.type = type;        this.type = type;
       knownMod = Hashtable.this.modCount;  
       count = 0;  
       idx = buckets.length;  
958      }      }
959    
960      /**      /**
# Line 965  public class Hashtable extends Dictionar Line 964  public class Hashtable extends Dictionar
964       */       */
965      public boolean hasNext()      public boolean hasNext()
966      {      {
967        if (knownMod != Hashtable.this.modCount)        if (knownMod != modCount)
968          throw new ConcurrentModificationException();          throw new ConcurrentModificationException();
969        return count < size;        return count > 0;
970      }      }
971    
972      /**      /**
# Line 978  public class Hashtable extends Dictionar Line 977  public class Hashtable extends Dictionar
977       */       */
978      public Object next()      public Object next()
979      {      {
980        if (knownMod != Hashtable.this.modCount)        if (knownMod != modCount)
981          throw new ConcurrentModificationException();          throw new ConcurrentModificationException();
982        if (count == size)        if (count == 0)
983          throw new NoSuchElementException();          throw new NoSuchElementException();
984        count++;        count--;
985        HashEntry e = null;        HashEntry e = next;
       if (next != null)  
         e = next;  
986    
987        while (e == null)        while (e == null)
988          {          e = buckets[--idx];
           e = buckets[--idx];  
         }  
989    
990        next = e.next;        next = e.next;
991        last = e;        last = e;
# Line 1001  public class Hashtable extends Dictionar Line 996  public class Hashtable extends Dictionar
996        return e;        return e;
997      }      }
998    
999      /**      /**
1000       * Removes from the backing Hashtable the last element which was fetched       * Removes from the backing Hashtable the last element which was fetched
1001       * with the <pre>next()</pre> method.       * with the <pre>next()</pre> method.
1002       * @throws ConcurrentModificationException if the hashtable was modified       * @throws ConcurrentModificationException if the hashtable was modified
1003       * @throws IllegalStateException if called when there is no last element       * @throws IllegalStateException if called when there is no last element
1004       */       */
1005      public void remove()      public void remove()
1006      {      {
1007        if (knownMod != Hashtable.this.modCount)        if (knownMod != modCount)
1008          throw new ConcurrentModificationException();          throw new ConcurrentModificationException();
1009        if (last == null)        if (last == null)
1010          throw new IllegalStateException();          throw new IllegalStateException();
1011    
1012        Hashtable.this.remove(last.key);        Hashtable.this.remove(last.key);
1013        knownMod++;        knownMod++;
       count--;  
1014        last = null;        last = null;
1015      }      }
1016    }    }
1017    
1018    
1019    /**    /**
1020     * Enumeration view of this Hashtable, providing sequential access to its     * Enumeration view of this Hashtable, providing sequential access to its
1021     * elements; this implementation is parameterized to provide access either     * elements; this implementation is parameterized to provide access either
1022     * to the keys or to the values in the Hashtable.     * to the keys or to the values in the Hashtable.
1023     *     *
1024     * <b>NOTE</b>: Enumeration is not safe if new elements are put in the table     * <b>NOTE</b>: Enumeration is not safe if new elements are put in the table
# Line 1039  public class Hashtable extends Dictionar Line 1033  public class Hashtable extends Dictionar
1033    class Enumerator implements Enumeration    class Enumerator implements Enumeration
1034    {    {
1035      /** "enum" of iterator types. */      /** "enum" of iterator types. */
1036      static final int KEYS = 0;      static final int KEYS = 0,
1037      /** "enum" of iterator types. */                       VALUES = 1;
     static final int VALUES = 1;  
1038    
1039      /**      /**
1040       * The type of this Iterator: {@link KEYS} or {@link VALUES}.       * The type of this Iterator: {@link #KEYS} or {@link #VALUES}.
1041       */       */
1042      int type;      int type;
1043      /** Current index in the physical hash table. */      /** Current index in the physical hash table. */
# Line 1056  public class Hashtable extends Dictionar Line 1049  public class Hashtable extends Dictionar
1049    
1050      /**      /**
1051       * Construct the enumeration.       * Construct the enumeration.
1052       * @param type either {@link KEYS} or {@link VALUES}.       * @param type either {@link #KEYS} or {@link #VALUES}.
1053       */       */
1054      Enumerator(int type)      Enumerator(int type)
1055      {      {
# Line 1076  public class Hashtable extends Dictionar Line 1069  public class Hashtable extends Dictionar
1069          e = last.next;          e = last.next;
1070    
1071        while (e == null && idx > 0)        while (e == null && idx > 0)
1072          {          e = buckets[--idx];
1073            e = buckets[--idx];  
         }  
1074        last = e;        last = e;
1075        return e;        return e;
1076      }      }
# Line 1092  public class Hashtable extends Dictionar Line 1084  public class Hashtable extends Dictionar
1084        if (next != null)        if (next != null)
1085          return true;          return true;
1086        next = nextEntry();        next = nextEntry();
1087        return (next != null);        return next != null;
1088      }      }
1089    
1090      /**      /**

Legend:
Removed from v.1.16  
changed lines
  Added in v.1.17

savannah-hackers-public@gnu.org
ViewVC Help
Powered by ViewVC 1.1.26