KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Acme > IntHashtable


1 // IntHashtable - a Hashtable that uses ints as the keys
2
//
3
// This is 90% based on JavaSoft's java.util.Hashtable.
4
//
5
// Visit the ACME Labs Java page for up-to-date versions of this and other
6
// fine Java utilities: http://www.acme.com/java/
7

8 package Acme;
9
10 import java.util.Dictionary JavaDoc;
11 import java.util.Enumeration JavaDoc;
12 import java.util.NoSuchElementException JavaDoc;
13
14 /// A Hashtable that uses ints as the keys.
15
// <P>
16
// Use just like java.util.Hashtable, except that the keys must be ints.
17
// This is much faster than creating a new Integer for each access.
18
// <P>
19
// <A HREF="../../resources/classes/Acme/IntHashtable.java">Fetch the software.</A><BR>
20
// <A HREF="../../resources/classes/Acme.tar.gz">Fetch the entire Acme package.</A>
21
// <P>
22
// @see java.util.Hashtable
23

24 public class IntHashtable extends Dictionary JavaDoc implements Cloneable JavaDoc {
25     /// The hash table data.
26
private IntHashtableEntry table[];
27
28     /// The total number of entries in the hash table.
29
private int count;
30
31     /// Rehashes the table when count exceeds this threshold.
32
private int threshold;
33
34     /// The load factor for the hashtable.
35
private float loadFactor;
36
37     /// Constructs a new, empty hashtable with the specified initial
38
// capacity and the specified load factor.
39
// @param initialCapacity the initial number of buckets
40
// @param loadFactor a number between 0.0 and 1.0, it defines
41
// the threshold for rehashing the hashtable into
42
// a bigger one.
43
// @exception IllegalArgumentException If the initial capacity
44
// is less than or equal to zero.
45
// @exception IllegalArgumentException If the load factor is
46
// less than or equal to zero.
47
public IntHashtable(int initialCapacity, float loadFactor) {
48         if (initialCapacity <= 0 || loadFactor <= 0.0)
49             throw new IllegalArgumentException JavaDoc();
50         this.loadFactor = loadFactor;
51         table = new IntHashtableEntry[initialCapacity];
52         threshold = (int) (initialCapacity * loadFactor);
53     }
54
55     /// Constructs a new, empty hashtable with the specified initial
56
// capacity.
57
// @param initialCapacity the initial number of buckets
58
public IntHashtable(int initialCapacity) {
59         this(initialCapacity, 0.75f);
60     }
61
62     /// Constructs a new, empty hashtable. A default capacity and load factor
63
// is used. Note that the hashtable will automatically grow when it gets
64
// full.
65
public IntHashtable() {
66         this(101, 0.75f);
67     }
68
69     /// Returns the number of elements contained in the hashtable.
70
public int size() {
71         return count;
72     }
73
74     /// Returns true if the hashtable contains no elements.
75
public boolean isEmpty() {
76         return count == 0;
77     }
78
79     /// Returns an enumeration of the hashtable's keys.
80
// @see IntHashtable#elements
81
public synchronized Enumeration JavaDoc keys() {
82         return new IntHashtableEnumerator(table, true);
83     }
84
85     /// Returns an enumeration of the elements. Use the Enumeration methods
86
// on the returned object to fetch the elements sequentially.
87
// @see IntHashtable#keys
88
public synchronized Enumeration JavaDoc elements() {
89         return new IntHashtableEnumerator(table, false);
90     }
91
92     /// Returns true if the specified object is an element of the hashtable.
93
// This operation is more expensive than the containsKey() method.
94
// @param value the value that we are looking for
95
// @exception NullPointerException If the value being searched
96
// for is equal to null.
97
// @see IntHashtable#containsKey
98
public synchronized boolean contains(Object JavaDoc value) {
99         if (value == null)
100             throw new NullPointerException JavaDoc();
101         IntHashtableEntry tab[] = table;
102         for (int i = tab.length; i-- > 0;) {
103             for (IntHashtableEntry e = tab[i]; e != null; e = e.next) {
104                 if (e.value.equals(value))
105                     return true;
106             }
107         }
108         return false;
109     }
110
111     /// Returns true if the collection contains an element for the key.
112
// @param key the key that we are looking for
113
// @see IntHashtable#contains
114
public synchronized boolean containsKey(int key) {
115         IntHashtableEntry tab[] = table;
116         int hash = key;
117         int index = (hash & 0x7FFFFFFF) % tab.length;
118         for (IntHashtableEntry e = tab[index]; e != null; e = e.next) {
119             if (e.hash == hash && e.key == key)
120                 return true;
121         }
122         return false;
123     }
124
125     /// Gets the object associated with the specified key in the
126
// hashtable.
127
// @param key the specified key
128
// @returns the element for the key or null if the key
129
// is not defined in the hash table.
130
// @see IntHashtable#put
131
public synchronized Object JavaDoc get(int key) {
132         IntHashtableEntry tab[] = table;
133         int hash = key;
134         int index = (hash & 0x7FFFFFFF) % tab.length;
135         for (IntHashtableEntry e = tab[index]; e != null; e = e.next) {
136             if (e.hash == hash && e.key == key)
137                 return e.value;
138         }
139         return null;
140     }
141
142     /// A get method that takes an Object, for compatibility with
143
// java.util.Dictionary. The Object must be an Integer.
144
public Object JavaDoc get(Object JavaDoc okey) {
145         if (!(okey instanceof Integer JavaDoc))
146             throw new InternalError JavaDoc("key is not an Integer");
147         Integer JavaDoc ikey = (Integer JavaDoc) okey;
148         int key = ikey.intValue();
149         return get(key);
150     }
151
152     /// Rehashes the content of the table into a bigger table.
153
// This method is called automatically when the hashtable's
154
// size exceeds the threshold.
155
protected void rehash() {
156         int oldCapacity = table.length;
157         IntHashtableEntry oldTable[] = table;
158
159         int newCapacity = oldCapacity * 2 + 1;
160         IntHashtableEntry newTable[] = new IntHashtableEntry[newCapacity];
161
162         threshold = (int) (newCapacity * loadFactor);
163         table = newTable;
164
165         for (int i = oldCapacity; i-- > 0;) {
166             for (IntHashtableEntry old = oldTable[i]; old != null;) {
167                 IntHashtableEntry e = old;
168                 old = old.next;
169
170                 int index = (e.hash & 0x7FFFFFFF) % newCapacity;
171                 e.next = newTable[index];
172                 newTable[index] = e;
173             }
174         }
175     }
176
177     /// Puts the specified element into the hashtable, using the specified
178
// key. The element may be retrieved by doing a get() with the same key.
179
// The key and the element cannot be null.
180
// @param key the specified key in the hashtable
181
// @param value the specified element
182
// @exception NullPointerException If the value of the element
183
// is equal to null.
184
// @see IntHashtable#get
185
// @return the old value of the key, or null if it did not have one.
186
public synchronized Object JavaDoc put(int key, Object JavaDoc value) {
187         // Make sure the value is not null.
188
if (value == null)
189             throw new NullPointerException JavaDoc();
190
191         // Makes sure the key is not already in the hashtable.
192
IntHashtableEntry tab[] = table;
193         int hash = key;
194         int index = (hash & 0x7FFFFFFF) % tab.length;
195         for (IntHashtableEntry e = tab[index]; e != null; e = e.next) {
196             if (e.hash == hash && e.key == key) {
197                 Object JavaDoc old = e.value;
198                 e.value = value;
199                 return old;
200             }
201         }
202
203         if (count >= threshold) {
204             // Rehash the table if the threshold is exceeded.
205
rehash();
206             return put(key, value);
207         }
208
209         // Creates the new entry.
210
IntHashtableEntry e = new IntHashtableEntry();
211         e.hash = hash;
212         e.key = key;
213         e.value = value;
214         e.next = tab[index];
215         tab[index] = e;
216         ++count;
217         return null;
218     }
219
220     /// A put method that takes an Object, for compatibility with
221
// java.util.Dictionary. The Object must be an Integer.
222
public Object JavaDoc put(Object JavaDoc okey, Object JavaDoc value) {
223         if (!(okey instanceof Integer JavaDoc))
224             throw new InternalError JavaDoc("key is not an Integer");
225         Integer JavaDoc ikey = (Integer JavaDoc) okey;
226         int key = ikey.intValue();
227         return put(key, value);
228     }
229
230     /// Removes the element corresponding to the key. Does nothing if the
231
// key is not present.
232
// @param key the key that needs to be removed
233
// @return the value of key, or null if the key was not found.
234
public synchronized Object JavaDoc remove(int key) {
235         IntHashtableEntry tab[] = table;
236         int hash = key;
237         int index = (hash & 0x7FFFFFFF) % tab.length;
238         for (IntHashtableEntry e = tab[index], prev = null; e != null; prev = e, e = e.next) {
239             if (e.hash == hash && e.key == key) {
240                 if (prev != null)
241                     prev.next = e.next;
242                 else
243                     tab[index] = e.next;
244                 --count;
245                 return e.value;
246             }
247         }
248         return null;
249     }
250
251     /// A remove method that takes an Object, for compatibility with
252
// java.util.Dictionary. The Object must be an Integer.
253
public Object JavaDoc remove(Object JavaDoc okey) {
254         if (!(okey instanceof Integer JavaDoc))
255             throw new InternalError JavaDoc("key is not an Integer");
256         Integer JavaDoc ikey = (Integer JavaDoc) okey;
257         int key = ikey.intValue();
258         return remove(key);
259     }
260
261     /// Clears the hash table so that it has no more elements in it.
262
public synchronized void clear() {
263         IntHashtableEntry tab[] = table;
264         for (int index = tab.length; --index >= 0;)
265             tab[index] = null;
266         count = 0;
267     }
268
269     /// Creates a clone of the hashtable. A shallow copy is made,
270
// the keys and elements themselves are NOT cloned. This is a
271
// relatively expensive operation.
272
public synchronized Object JavaDoc clone() {
273         try {
274             IntHashtable t = (IntHashtable) super.clone();
275             t.table = new IntHashtableEntry[table.length];
276             for (int i = table.length; i-- > 0;)
277                 t.table[i] = (table[i] != null) ?
278                         (IntHashtableEntry) table[i].clone() : null;
279             return t;
280         } catch (CloneNotSupportedException JavaDoc e) {
281             // This shouldn't happen, since we are Cloneable.
282
throw new InternalError JavaDoc();
283         }
284     }
285
286     /// Converts to a rather lengthy String.
287
public synchronized String JavaDoc toString() {
288         int max = size() - 1;
289         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
290         Enumeration JavaDoc k = keys();
291         Enumeration JavaDoc e = elements();
292         buf.append("{");
293
294         for (int i = 0; i <= max; ++i) {
295             String JavaDoc s1 = k.nextElement().toString();
296             String JavaDoc s2 = e.nextElement().toString();
297             buf.append(s1 + "=" + s2);
298             if (i < max)
299                 buf.append(", ");
300         }
301         buf.append("}");
302         return buf.toString();
303     }
304 }
305
306
307 class IntHashtableEntry {
308     int hash;
309     int key;
310     Object JavaDoc value;
311     IntHashtableEntry next;
312
313     protected Object JavaDoc clone() {
314         IntHashtableEntry entry = new IntHashtableEntry();
315         entry.hash = hash;
316         entry.key = key;
317         entry.value = value;
318         entry.next = (next != null) ? (IntHashtableEntry) next.clone() : null;
319         return entry;
320     }
321 }
322
323
324 class IntHashtableEnumerator implements Enumeration JavaDoc {
325     boolean keys;
326     int index;
327     IntHashtableEntry table[];
328     IntHashtableEntry entry;
329
330     IntHashtableEnumerator(IntHashtableEntry table[], boolean keys) {
331         this.table = table;
332         this.keys = keys;
333         this.index = table.length;
334     }
335
336     public boolean hasMoreElements() {
337         if (entry != null)
338             return true;
339         while (index-- > 0)
340             if ((entry = table[index]) != null)
341                 return true;
342         return false;
343     }
344
345     public Object JavaDoc nextElement() {
346         if (entry == null)
347             while ((index-- > 0) && ((entry = table[index]) == null))
348                 ;
349         if (entry != null) {
350             IntHashtableEntry e = entry;
351             entry = e.next;
352             return keys ? new Integer JavaDoc(e.key) : e.value;
353         }
354         throw new NoSuchElementException JavaDoc("IntHashtableEnumerator");
355     }
356 }
357
Popular Tags