1 /* Hashtable.java -- a class providing a basic hashtable data structure,
2 mapping Object --> Object
3 Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 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)
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
41 import java
.io
.IOException
;
42 import java
.io
.Serializable
;
43 import java
.io
.ObjectInputStream
;
44 import java
.io
.ObjectOutputStream
;
46 // NOTE: This implementation is very similar to that of HashMap. If you fix
47 // a bug in here, chances are you should make a similar change to the HashMap
51 * A class which implements a hashtable data structure.
54 * This implementation of Hashtable uses a hash-bucket approach. That is:
55 * linear probing and rehashing is avoided; instead, each hashed value maps
56 * to a simple linked-list which, in the best case, only has one node.
57 * 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 * the worst case for all of these (if all keys hash to the same bucket).
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.
69 * Being a hybrid of old and new, Hashtable has methods which provide redundant
70 * capability, but with subtle and even crucial differences.
71 * For example, one can iterate over various aspects of a Hashtable with
72 * either an Iterator (which is the JDK-1.2 way of doing things) or with an
73 * Enumeration. The latter can end up in an undefined state if the Hashtable
74 * changes while the Enumeration is open.
77 * Unlike HashMap, Hashtable does not accept `null' as a key value. Also,
78 * all accesses are synchronized: in a single thread environment, this is
79 * expensive, but in a multi-thread environment, this saves you the effort
80 * of extra synchronization. However, the old-style enumerators are not
81 * synchronized, because they can lead to unspecified behavior even if
82 * they were synchronized. You have been warned.
85 * The iterators are <i>fail-fast</i>, meaning that any structural
86 * modification, except for <code>remove()</code> called on the iterator
87 * itself, cause the iterator to throw a
88 * <code>ConcurrentModificationException</code> rather than exhibit
89 * non-deterministic behavior.
91 * @author Jon Zeppieri
93 * @author Bryce McKinlay
94 * @author Eric Blake <ebb9@email.byu.edu>
97 * @see IdentityHashMap
100 * @status updated to 1.4
102 public class Hashtable
extends Dictionary
103 implements Map
, Cloneable
, Serializable
105 // WARNING: Hashtable is a CORE class in the bootstrap cycle. See the
106 // comments in vm/reference/java/lang/Runtime for implications of this fact.
108 /** Default number of buckets. This is the value the JDK 1.3 uses. Some
109 * early documentation specified this value as 101. That is incorrect.
111 private static final int DEFAULT_CAPACITY
= 11;
113 /** An "enum" of iterator types. */
114 // Package visible for use by nested classes.
115 static final int KEYS
= 0,
120 * The default load factor; this is explicitly specified by the spec.
122 private static final float DEFAULT_LOAD_FACTOR
= 0.75f
;
125 * Compatible with JDK 1.0+.
127 private static final long serialVersionUID
= 1421746759512286392L;
130 * The rounded product of the capacity and the load factor; when the number
131 * of elements exceeds the threshold, the Hashtable calls
132 * <code>rehash()</code>.
135 private int threshold
;
138 * Load factor of this Hashtable: used in computing the threshold.
141 private final float loadFactor
;
144 * Array containing the actual key-value mappings.
146 // Package visible for use by nested classes.
147 transient HashEntry
[] buckets
;
150 * Counts the number of modifications this Hashtable has undergone, used
151 * by Iterators to know when to throw ConcurrentModificationExceptions.
153 // Package visible for use by nested classes.
154 transient int modCount
;
157 * The size of this Hashtable: denotes the number of key-value pairs.
159 // Package visible for use by nested classes.
163 * The cache for {@link #keySet()}.
165 private transient Set keys
;
168 * The cache for {@link #values()}.
170 private transient Collection values
;
173 * The cache for {@link #entrySet()}.
175 private transient Set entries
;
178 * Class to represent an entry in the hash table. Holds a single key-value
179 * pair. A Hashtable Entry is identical to a HashMap Entry, except that
180 * `null' is not allowed for keys and values.
182 private static final class HashEntry
extends AbstractMap
.BasicMapEntry
184 /** The next entry in the linked list. */
188 * Simple constructor.
189 * @param key the key, already guaranteed non-null
190 * @param value the value, already guaranteed non-null
192 HashEntry(Object key
, Object value
)
199 * @param newValue the new value
200 * @return the prior value
201 * @throws NullPointerException if <code>newVal</code> is null
203 public Object
setValue(Object newVal
)
206 throw new NullPointerException();
207 return super.setValue(newVal
);
212 * Construct a new Hashtable with the default capacity (11) and the default
213 * load factor (0.75).
217 this(DEFAULT_CAPACITY
, DEFAULT_LOAD_FACTOR
);
221 * Construct a new Hashtable from the given Map, with initial capacity
222 * the greater of the size of <code>m</code> or the default of 11.
225 * Every element in Map m will be put into this new Hashtable.
227 * @param m a Map whose key / value pairs will be put into
228 * the new Hashtable. <b>NOTE: key / value pairs
229 * are not cloned in this constructor.</b>
230 * @throws NullPointerException if m is null, or if m contains a mapping
234 public Hashtable(Map m
)
236 this(Math
.max(m
.size() * 2, DEFAULT_CAPACITY
), DEFAULT_LOAD_FACTOR
);
241 * Construct a new Hashtable with a specific inital capacity and
242 * default load factor of 0.75.
244 * @param initialCapacity the initial capacity of this Hashtable (>= 0)
245 * @throws IllegalArgumentException if (initialCapacity < 0)
247 public Hashtable(int initialCapacity
)
249 this(initialCapacity
, DEFAULT_LOAD_FACTOR
);
253 * Construct a new Hashtable with a specific initial capacity and
256 * @param initialCapacity the initial capacity (>= 0)
257 * @param loadFactor the load factor (> 0, not NaN)
258 * @throws IllegalArgumentException if (initialCapacity < 0) ||
259 * ! (loadFactor > 0.0)
261 public Hashtable(int initialCapacity
, float loadFactor
)
263 if (initialCapacity
< 0)
264 throw new IllegalArgumentException("Illegal Capacity: "
266 if (! (loadFactor
> 0)) // check for NaN too
267 throw new IllegalArgumentException("Illegal Load: " + loadFactor
);
269 if (initialCapacity
== 0)
271 buckets
= new HashEntry
[initialCapacity
];
272 this.loadFactor
= loadFactor
;
273 threshold
= (int) (initialCapacity
* loadFactor
);
277 * Returns the number of key-value mappings currently in this hashtable.
280 public synchronized int size()
286 * Returns true if there are no key-value mappings currently in this table.
287 * @return <code>size() == 0</code>
289 public synchronized boolean isEmpty()
295 * Return an enumeration of the keys of this table. There's no point
296 * in synchronizing this, as you have already been warned that the
297 * enumeration is not specified to be thread-safe.
303 public Enumeration
keys()
305 return new Enumerator(KEYS
);
309 * Return an enumeration of the values of this table. There's no point
310 * in synchronizing this, as you have already been warned that the
311 * enumeration is not specified to be thread-safe.
317 public Enumeration
elements()
319 return new Enumerator(VALUES
);
323 * Returns true if this Hashtable contains a value <code>o</code>,
324 * such that <code>o.equals(value)</code>. This is the same as
325 * <code>containsValue()</code>, and is O(n).
328 * @param value the value to search for in this Hashtable
329 * @return true if at least one key maps to the value
330 * @throws NullPointerException if <code>value</code> is null
331 * @see #containsValue(Object)
332 * @see #containsKey(Object)
334 public synchronized boolean contains(Object value
)
336 return containsValue(value
);
340 * Returns true if this Hashtable contains a value <code>o</code>, such that
341 * <code>o.equals(value)</code>. This is the new API for the old
342 * <code>contains()</code>.
344 * @param value the value to search for in this Hashtable
345 * @return true if at least one key maps to the value
346 * @see #contains(Object)
347 * @see #containsKey(Object)
348 * @throws NullPointerException if <code>value</code> is null
351 public boolean containsValue(Object value
)
353 for (int i
= buckets
.length
- 1; i
>= 0; i
--)
355 HashEntry e
= buckets
[i
];
358 if (value
.equals(e
.value
))
364 // Must throw on null argument even if the table is empty
366 throw new NullPointerException();
372 * Returns true if the supplied object <code>equals()</code> a key
375 * @param key the key to search for in this Hashtable
376 * @return true if the key is in the table
377 * @throws NullPointerException if key is null
378 * @see #containsValue(Object)
380 public synchronized boolean containsKey(Object key
)
383 HashEntry e
= buckets
[idx
];
386 if (key
.equals(e
.key
))
394 * Return the value in this Hashtable associated with the supplied key,
395 * or <code>null</code> if the key maps to nothing.
397 * @param key the key for which to fetch an associated value
398 * @return what the key maps to, if present
399 * @throws NullPointerException if key is null
400 * @see #put(Object, Object)
401 * @see #containsKey(Object)
403 public synchronized Object
get(Object key
)
406 HashEntry e
= buckets
[idx
];
409 if (key
.equals(e
.key
))
417 * Puts the supplied value into the Map, mapped by the supplied key.
418 * Neither parameter may be null. The value may be retrieved by any
419 * object which <code>equals()</code> this key.
421 * @param key the key used to locate the value
422 * @param value the value to be stored in the table
423 * @return the prior mapping of the key, or null if there was none
424 * @throws NullPointerException if key or value is null
426 * @see Object#equals(Object)
428 public synchronized Object
put(Object key
, Object value
)
431 HashEntry e
= buckets
[idx
];
433 // Check if value is null since it is not permitted.
435 throw new NullPointerException();
439 if (key
.equals(e
.key
))
441 // Bypass e.setValue, since we already know value is non-null.
452 // At this point, we know we need to add a new entry.
454 if (++size
> threshold
)
457 // Need a new hash value to suit the bigger table.
461 e
= new HashEntry(key
, value
);
463 e
.next
= buckets
[idx
];
470 * Removes from the table and returns the value which is mapped by the
471 * supplied key. If the key maps to nothing, then the table remains
472 * unchanged, and <code>null</code> is returned.
474 * @param key the key used to locate the value to remove
475 * @return whatever the key mapped to, if present
477 public synchronized Object
remove(Object key
)
480 HashEntry e
= buckets
[idx
];
481 HashEntry last
= null;
485 if (key
.equals(e
.key
))
489 buckets
[idx
] = e
.next
;
502 * Copies all elements of the given map into this hashtable. However, no
503 * mapping can contain null as key or value. If this table already has
504 * a mapping for a key, the new mapping replaces the current one.
506 * @param m the map to be hashed into this
507 * @throws NullPointerException if m is null, or contains null keys or values
509 public synchronized void putAll(Map m
)
511 Iterator itr
= m
.entrySet().iterator();
513 for (int msize
= m
.size(); msize
> 0; msize
--)
515 Map
.Entry e
= (Map
.Entry
) itr
.next();
516 // Optimize in case the Entry is one of our own.
517 if (e
instanceof AbstractMap
.BasicMapEntry
)
519 AbstractMap
.BasicMapEntry entry
= (AbstractMap
.BasicMapEntry
) e
;
520 put(entry
.key
, entry
.value
);
524 put(e
.getKey(), e
.getValue());
530 * Clears the hashtable so it has no keys. This is O(1).
532 public synchronized void clear()
537 Arrays
.fill(buckets
, null);
543 * Returns a shallow clone of this Hashtable. The Map itself is cloned,
544 * but its contents are not. This is O(n).
548 public synchronized Object
clone()
550 Hashtable copy
= null;
553 copy
= (Hashtable
) super.clone();
555 catch (CloneNotSupportedException x
)
557 // This is impossible.
559 copy
.buckets
= new HashEntry
[buckets
.length
];
560 copy
.putAllInternal(this);
569 * Converts this Hashtable to a String, surrounded by braces, and with
570 * key/value pairs listed with an equals sign between, separated by a
571 * comma and space. For example, <code>"{a=1, b=2}"</code>.<p>
573 * NOTE: if the <code>toString()</code> method of any key or value
574 * throws an exception, this will fail for the same reason.
576 * @return the string representation
578 public synchronized String
toString()
580 // Since we are already synchronized, and entrySet().iterator()
581 // would repeatedly re-lock/release the monitor, we directly use the
582 // unsynchronized HashIterator instead.
583 Iterator entries
= new HashIterator(ENTRIES
);
584 StringBuffer r
= new StringBuffer("{");
585 for (int pos
= size
; pos
> 0; pos
--)
587 r
.append(entries
.next());
596 * Returns a "set view" of this Hashtable's keys. The set is backed by
597 * the hashtable, so changes in one show up in the other. The set supports
598 * element removal, but not element addition. The set is properly
599 * synchronized on the original hashtable. Sun has not documented the
600 * proper interaction of null with this set, but has inconsistent behavior
601 * in the JDK. Therefore, in this implementation, contains, remove,
602 * containsAll, retainAll, removeAll, and equals just ignore a null key
603 * rather than throwing a {@link NullPointerException}.
605 * @return a set view of the keys
614 // Create a synchronized AbstractSet with custom implementations of
615 // those methods that can be overridden easily and efficiently.
616 Set r
= new AbstractSet()
623 public Iterator
iterator()
625 return new HashIterator(KEYS
);
630 Hashtable
.this.clear();
633 public boolean contains(Object o
)
637 return containsKey(o
);
640 public boolean remove(Object o
)
642 return Hashtable
.this.remove(o
) != null;
645 // We must specify the correct object to synchronize upon, hence the
646 // use of a non-public API
647 keys
= new Collections
.SynchronizedSet(this, r
);
653 * Returns a "collection view" (or "bag view") of this Hashtable's values.
654 * The collection is backed by the hashtable, so changes in one show up
655 * in the other. The collection supports element removal, but not element
656 * addition. The collection is properly synchronized on the original
657 * hashtable. Sun has not documented the proper interaction of null with
658 * this set, but has inconsistent behavior in the JDK. Therefore, in this
659 * implementation, contains, remove, containsAll, retainAll, removeAll, and
660 * equals just ignore a null value rather than throwing a
661 * {@link NullPointerException}.
663 * @return a bag view of the values
668 public Collection
values()
672 // We don't bother overriding many of the optional methods, as doing so
673 // wouldn't provide any significant performance advantage.
674 Collection r
= new AbstractCollection()
681 public Iterator
iterator()
683 return new HashIterator(VALUES
);
688 Hashtable
.this.clear();
691 // We must specify the correct object to synchronize upon, hence the
692 // use of a non-public API
693 values
= new Collections
.SynchronizedCollection(this, r
);
699 * Returns a "set view" of this Hashtable's entries. The set is backed by
700 * the hashtable, so changes in one show up in the other. The set supports
701 * element removal, but not element addition. The set is properly
702 * synchronized on the original hashtable. Sun has not documented the
703 * proper interaction of null with this set, but has inconsistent behavior
704 * in the JDK. Therefore, in this implementation, contains, remove,
705 * containsAll, retainAll, removeAll, and equals just ignore a null entry,
706 * or an entry with a null key or value, rather than throwing a
707 * {@link NullPointerException}. However, calling entry.setValue(null)
711 * Note that the iterators for all three views, from keySet(), entrySet(),
712 * and values(), traverse the hashtable in the same sequence.
714 * @return a set view of the entries
720 public Set
entrySet()
724 // Create an AbstractSet with custom implementations of those methods
725 // that can be overridden easily and efficiently.
726 Set r
= new AbstractSet()
733 public Iterator
iterator()
735 return new HashIterator(ENTRIES
);
740 Hashtable
.this.clear();
743 public boolean contains(Object o
)
745 return getEntry(o
) != null;
748 public boolean remove(Object o
)
750 HashEntry e
= getEntry(o
);
753 Hashtable
.this.remove(e
.key
);
759 // We must specify the correct object to synchronize upon, hence the
760 // use of a non-public API
761 entries
= new Collections
.SynchronizedSet(this, r
);
767 * Returns true if this Hashtable equals the supplied Object <code>o</code>.
768 * As specified by Map, this is:
770 * (o instanceof Map) && entrySet().equals(((Map) o).entrySet());
773 * @param o the object to compare to
774 * @return true if o is an equal map
777 public boolean equals(Object o
)
779 // no need to synchronize, entrySet().equals() does that
782 if (!(o
instanceof Map
))
785 return entrySet().equals(((Map
) o
).entrySet());
789 * Returns the hashCode for this Hashtable. As specified by Map, this is
790 * the sum of the hashCodes of all of its Map.Entry objects
792 * @return the sum of the hashcodes of the entries
795 public synchronized int hashCode()
797 // Since we are already synchronized, and entrySet().iterator()
798 // would repeatedly re-lock/release the monitor, we directly use the
799 // unsynchronized HashIterator instead.
800 Iterator itr
= new HashIterator(ENTRIES
);
802 for (int pos
= size
; pos
> 0; pos
--)
803 hashcode
+= itr
.next().hashCode();
809 * Helper method that returns an index in the buckets array for `key'
810 * based on its hashCode().
813 * @return the bucket number
814 * @throws NullPointerException if key is null
816 private int hash(Object key
)
818 // Note: Inline Math.abs here, for less method overhead, and to avoid
819 // a bootstrap dependency, since Math relies on native methods.
820 int hash
= key
.hashCode() % buckets
.length
;
821 return hash
< 0 ?
-hash
: hash
;
825 * Helper method for entrySet(), which matches both key and value
826 * simultaneously. Ignores null, as mentioned in entrySet().
828 * @param o the entry to match
829 * @return the matching entry, if found, or null
832 // Package visible, for use in nested classes.
833 HashEntry
getEntry(Object o
)
835 if (! (o
instanceof Map
.Entry
))
837 Object key
= ((Map
.Entry
) o
).getKey();
842 HashEntry e
= buckets
[idx
];
853 * A simplified, more efficient internal implementation of putAll(). The
854 * Map constructor and clone() should not call putAll or put, in order to
855 * be compatible with the JDK implementation with respect to subclasses.
857 * @param m the map to initialize this from
859 void putAllInternal(Map m
)
861 Iterator itr
= m
.entrySet().iterator();
862 int msize
= m
.size();
865 for (; msize
> 0; msize
--)
867 Map
.Entry e
= (Map
.Entry
) itr
.next();
868 Object key
= e
.getKey();
870 HashEntry he
= new HashEntry(key
, e
.getValue());
871 he
.next
= buckets
[idx
];
877 * Increases the size of the Hashtable and rehashes all keys to new array
878 * indices; this is called when the addition of a new value would cause
879 * size() > threshold. Note that the existing Entry objects are reused in
880 * the new hash table.
883 * This is not specified, but the new size is twice the current size plus
884 * one; this number is not always prime, unfortunately. This implementation
885 * is not synchronized, as it is only invoked from synchronized methods.
887 protected void rehash()
889 HashEntry
[] oldBuckets
= buckets
;
891 int newcapacity
= (buckets
.length
* 2) + 1;
892 threshold
= (int) (newcapacity
* loadFactor
);
893 buckets
= new HashEntry
[newcapacity
];
895 for (int i
= oldBuckets
.length
- 1; i
>= 0; i
--)
897 HashEntry e
= oldBuckets
[i
];
900 int idx
= hash(e
.key
);
901 HashEntry dest
= buckets
[idx
];
905 while (dest
.next
!= null)
914 HashEntry next
= e
.next
;
922 * Serializes this object to the given stream.
924 * @param s the stream to write to
925 * @throws IOException if the underlying stream fails
926 * @serialData the <i>capacity</i> (int) that is the length of the
927 * bucket array, the <i>size</i> (int) of the hash map
928 * are emitted first. They are followed by size entries,
929 * each consisting of a key (Object) and a value (Object).
931 private synchronized void writeObject(ObjectOutputStream s
)
934 // Write the threshold and loadFactor fields.
935 s
.defaultWriteObject();
937 s
.writeInt(buckets
.length
);
939 // Since we are already synchronized, and entrySet().iterator()
940 // would repeatedly re-lock/release the monitor, we directly use the
941 // unsynchronized HashIterator instead.
942 Iterator it
= new HashIterator(ENTRIES
);
945 HashEntry entry
= (HashEntry
) it
.next();
946 s
.writeObject(entry
.key
);
947 s
.writeObject(entry
.value
);
952 * Deserializes this object from the given stream.
954 * @param s the stream to read from
955 * @throws ClassNotFoundException if the underlying stream fails
956 * @throws IOException if the underlying stream fails
957 * @serialData the <i>capacity</i> (int) that is the length of the
958 * bucket array, the <i>size</i> (int) of the hash map
959 * are emitted first. They are followed by size entries,
960 * each consisting of a key (Object) and a value (Object).
962 private void readObject(ObjectInputStream s
)
963 throws IOException
, ClassNotFoundException
965 // Read the threshold and loadFactor fields.
966 s
.defaultReadObject();
968 // Read and use capacity.
969 buckets
= new HashEntry
[s
.readInt()];
970 int len
= s
.readInt();
972 // Read and use key/value pairs.
973 // TODO: should we be defensive programmers, and check for illegal nulls?
975 put(s
.readObject(), s
.readObject());
979 * A class which implements the Iterator interface and is used for
980 * iterating over Hashtables.
981 * This implementation is parameterized to give a sequential view of
982 * keys, values, or entries; it also allows the removal of elements,
983 * as per the Javasoft spec. Note that it is not synchronized; this is
984 * a performance enhancer since it is never exposed externally and is
985 * only used within synchronized blocks above.
987 * @author Jon Zeppieri
989 private final class HashIterator
implements Iterator
992 * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
993 * or {@link #ENTRIES}.
997 * The number of modifications to the backing Hashtable that we know about.
999 int knownMod
= modCount
;
1000 /** The number of elements remaining to be returned by next(). */
1002 /** Current index in the physical hash table. */
1003 int idx
= buckets
.length
;
1004 /** The last Entry returned by a next() call. */
1007 * The next entry that should be returned by next(). It is set to something
1008 * if we're iterating through a bucket that contains multiple linked
1009 * entries. It is null if next() needs to find a new bucket.
1014 * Construct a new HashIterator with the supplied type.
1015 * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
1017 HashIterator(int type
)
1023 * Returns true if the Iterator has more elements.
1024 * @return true if there are more elements
1025 * @throws ConcurrentModificationException if the hashtable was modified
1027 public boolean hasNext()
1029 if (knownMod
!= modCount
)
1030 throw new ConcurrentModificationException();
1035 * Returns the next element in the Iterator's sequential view.
1036 * @return the next element
1037 * @throws ConcurrentModificationException if the hashtable was modified
1038 * @throws NoSuchElementException if there is none
1040 public Object
next()
1042 if (knownMod
!= modCount
)
1043 throw new ConcurrentModificationException();
1045 throw new NoSuchElementException();
1062 * Removes from the backing Hashtable the last element which was fetched
1063 * with the <code>next()</code> method.
1064 * @throws ConcurrentModificationException if the hashtable was modified
1065 * @throws IllegalStateException if called when there is no last element
1067 public void remove()
1069 if (knownMod
!= modCount
)
1070 throw new ConcurrentModificationException();
1072 throw new IllegalStateException();
1074 Hashtable
.this.remove(last
.key
);
1078 } // class HashIterator
1082 * Enumeration view of this Hashtable, providing sequential access to its
1083 * elements; this implementation is parameterized to provide access either
1084 * to the keys or to the values in the Hashtable.
1086 * <b>NOTE</b>: Enumeration is not safe if new elements are put in the table
1087 * as this could cause a rehash and we'd completely lose our place. Even
1088 * without a rehash, it is undetermined if a new element added would
1089 * appear in the enumeration. The spec says nothing about this, but
1090 * the "Java Class Libraries" book infers that modifications to the
1091 * hashtable during enumeration causes indeterminate results. Don't do it!
1093 * @author Jon Zeppieri
1095 private final class Enumerator
implements Enumeration
1098 * The type of this Iterator: {@link #KEYS} or {@link #VALUES}.
1101 /** The number of elements remaining to be returned by next(). */
1103 /** Current index in the physical hash table. */
1104 int idx
= buckets
.length
;
1106 * Entry which will be returned by the next nextElement() call. It is
1107 * set if we are iterating through a bucket with multiple entries, or null
1108 * if we must look in the next bucket.
1113 * Construct the enumeration.
1114 * @param type either {@link #KEYS} or {@link #VALUES}.
1116 Enumerator(int type
)
1122 * Checks whether more elements remain in the enumeration.
1123 * @return true if nextElement() will not fail.
1125 public boolean hasMoreElements()
1131 * Returns the next element.
1132 * @return the next element
1133 * @throws NoSuchElementException if there is none.
1135 public Object
nextElement()
1138 throw new NoSuchElementException("Hashtable Enumerator");
1146 return type
== VALUES ? e
.value
: e
.key
;
1148 } // class Enumerator
1149 } // class Hashtable