KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > versant > core > util > IntObjectHashMap


1
2 /*
3  * Copyright (c) 1998 - 2005 Versant Corporation
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  * Versant Corporation - initial API and implementation
11  */

12 package com.versant.core.util;
13
14 import java.io.IOException JavaDoc;
15 import java.io.Serializable JavaDoc;
16
17 /**
18  * Specialized HashMap mapping int to Object. This is a cut and paste of
19  * java.util.HashMap with the key hardcoded as int and some non-required
20  * functionality removed.
21  */

22 public final class IntObjectHashMap implements Serializable JavaDoc {
23
24     /**
25      * The default initial capacity - MUST be a power of two.
26      */

27     private static final int DEFAULT_INITIAL_CAPACITY = 16;
28
29     /**
30      * The maximum capacity, used if a higher value is implicitly specified
31      * by either of the constructors with arguments.
32      * MUST be a power of two <= 1<<30.
33      */

34     private static final int MAXIMUM_CAPACITY = 1 << 30;
35
36     /**
37      * The load factor used when none specified in constructor.
38      */

39     private static final float DEFAULT_LOAD_FACTOR = 0.75f;
40
41     /**
42      * The table, resized as necessary. Length MUST Always be a power of two.
43      */

44     private transient Entry[] table;
45
46     /**
47      * The number of key-value mappings contained in this identity hash map.
48      */

49     private transient int size;
50
51     /**
52      * The next size value at which to resize (capacity * load factor).
53      *
54      * @serial
55      */

56     private int threshold;
57
58     /**
59      * The load factor for the hash table.
60      *
61      * @serial
62      */

63     private final float loadFactor;
64
65     /**
66      * Constructs an empty <tt>IntObjectHashMap</tt> with the specified initial
67      * capacity and load factor.
68      *
69      * @param initialCapacity The initial capacity.
70      * @param loadFactor The load factor.
71      * @throws IllegalArgumentException if the initial capacity is negative
72      * or the load factor is nonpositive.
73      */

74     public IntObjectHashMap(int initialCapacity, float loadFactor) {
75         if (initialCapacity < 0) {
76             throw new IllegalArgumentException JavaDoc("Illegal initial capacity: " +
77                     initialCapacity);
78         }
79         if (initialCapacity > MAXIMUM_CAPACITY) {
80             initialCapacity = MAXIMUM_CAPACITY;
81         }
82         if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
83             throw new IllegalArgumentException JavaDoc("Illegal load factor: " +
84                     loadFactor);
85         }
86
87         // Find a power of 2 >= initialCapacity
88
int capacity = 1;
89         while (capacity < initialCapacity) {
90             capacity <<= 1;
91         }
92
93         this.loadFactor = loadFactor;
94         threshold = (int)(capacity * loadFactor);
95         table = new Entry[capacity];
96     }
97
98     /**
99      * Constructs an empty <tt>IntObjectHashMap</tt> with the specified initial
100      * capacity and the default load factor (0.75).
101      *
102      * @param initialCapacity the initial capacity.
103      * @throws IllegalArgumentException if the initial capacity is negative.
104      */

105     public IntObjectHashMap(int initialCapacity) {
106         this(initialCapacity, DEFAULT_LOAD_FACTOR);
107     }
108
109     /**
110      * Constructs an empty <tt>IntObjectHashMap</tt> with the default initial capacity
111      * (16) and the default load factor (0.75).
112      */

113     public IntObjectHashMap() {
114         this.loadFactor = DEFAULT_LOAD_FACTOR;
115         threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
116         table = new Entry[DEFAULT_INITIAL_CAPACITY];
117     }
118
119     /**
120      * Returns a string representation of this map. The string representation
121      * consists of a list of key-value mappings in the order returned by the
122      * map's <tt>entrySet</tt> view's iterator, enclosed in braces
123      * (<tt>"{}"</tt>). Adjacent mappings are separated by the characters
124      * <tt>", "</tt> (comma and space). Each key-value mapping is rendered as
125      * the key followed by an equals sign (<tt>"="</tt>) followed by the
126      * associated value. Keys and values are converted to strings as by
127      * <tt>String.valueOf(Object)</tt>.<p>
128      * <p/>
129      * This implementation creates an empty string buffer, appends a left
130      * brace, and iterates over the map's <tt>entrySet</tt> view, appending
131      * the string representation of each <tt>map.entry</tt> in turn. After
132      * appending each entry except the last, the string <tt>", "</tt> is
133      * appended. Finally a right brace is appended. A string is obtained
134      * from the stringbuffer, and returned.
135      *
136      * @return a String representation of this map.
137      */

138     public String JavaDoc toString() {
139         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
140         buf.append("{");
141         for (int i = 0; i < table.length; i++) {
142             Entry e = table[i];
143             for (; e != null; e = e.next) {
144                 int key = e.key;
145                 Object JavaDoc value = e.getValue();
146                 buf.append(key + "=" + (value == this ? "(this Map)" : value));
147             }
148         }
149         buf.append("}");
150         return buf.toString();
151     }
152
153     /**
154      * Returns the number of key-value mappings in this map.
155      *
156      * @return the number of key-value mappings in this map.
157      */

158     public int size() {
159         return size;
160     }
161
162     /**
163      * Returns <tt>true</tt> if this map contains no key-value mappings.
164      *
165      * @return <tt>true</tt> if this map contains no key-value mappings.
166      */

167     public boolean isEmpty() {
168         return size == 0;
169     }
170
171     /**
172      * Returns the value to which the specified key is mapped in this identity
173      * hash map, or <tt>null</tt> if the map contains no mapping for this key.
174      * A return value of <tt>null</tt> does not <i>necessarily</i> indicate
175      * that the map contains no mapping for the key; it is also possible that
176      * the map explicitly maps the key to <tt>null</tt>. The
177      * <tt>containsKey</tt> method may be used to distinguish these two cases.
178      *
179      * @param key the key whose associated value is to be returned.
180      * @return the value to which this map maps the specified key, or
181      * <tt>null</tt> if the map contains no mapping for this key.
182      */

183     public Object JavaDoc get(int key) {
184         int i = key & (table.length - 1);
185         Entry e = table[i];
186         while (true) {
187             if (e == null) {
188                 return e;
189             }
190             if (key == e.key) {
191                 return e.value;
192             }
193             e = e.next;
194         }
195     }
196
197     /**
198      * Returns <tt>true</tt> if this map contains a mapping for the
199      * specified key.
200      *
201      * @param key The key whose presence in this map is to be tested
202      * @return <tt>true</tt> if this map contains a mapping for the specified
203      * key.
204      */

205     public boolean containsKey(int key) {
206         int i = key & (table.length - 1);
207         Entry e = table[i];
208         while (e != null) {
209             if (key == e.key) {
210                 return true;
211             }
212             e = e.next;
213         }
214         return false;
215     }
216
217     /**
218      * Associates the specified value with the specified key in this map.
219      * If the map previously contained a mapping for this key, the old
220      * value is replaced.
221      *
222      * @param key key with which the specified value is to be associated.
223      * @param value value to be associated with the specified key.
224      * @return previous value associated with specified key, or <tt>null</tt>
225      * if there was no mapping for key. A <tt>null</tt> return can
226      * also indicate that the IntObjectHashMap previously associated
227      * <tt>null</tt> with the specified key.
228      */

229     public Object JavaDoc put(int key, Object JavaDoc value) {
230         int i = key & (table.length - 1);
231         for (Entry e = table[i]; e != null; e = e.next) {
232             if (key == e.key) {
233                 Object JavaDoc oldValue = e.value;
234                 e.value = value;
235                 return oldValue;
236             }
237         }
238         addEntry(key, value, i);
239         return null;
240     }
241
242     /**
243      * This method is used instead of put by constructors and
244      * pseudoconstructors (clone, readObject). It does not resize the table,
245      * check for comodification, etc. It calls createEntry rather than
246      * addEntry.
247      */

248     private void putForCreate(int key, Object JavaDoc value) {
249         int i = key & (table.length - 1);
250
251         /**
252          * Look for preexisting entry for key. This will never happen for
253          * clone or deserialize. It will only happen for construction if the
254          * input Map is a sorted map whose ordering is inconsistent w/ equals.
255          */

256         for (Entry e = table[i]; e != null; e = e.next) {
257             if (key == e.key) {
258                 e.value = value;
259                 return;
260             }
261         }
262         createEntry(key, value, i);
263     }
264
265     /**
266      * Rehashes the contents of this map into a new array with a
267      * larger capacity. This method is called automatically when the
268      * number of keys in this map reaches its threshold.
269      * <p/>
270      * If current capacity is MAXIMUM_CAPACITY, this method does not
271      * resize the map, but but sets threshold to Integer.MAX_VALUE.
272      * This has the effect of preventing future calls.
273      *
274      * @param newCapacity the new capacity, MUST be a power of two;
275      * must be greater than current capacity unless current
276      * capacity is MAXIMUM_CAPACITY (in which case value
277      * is irrelevant).
278      */

279     private void resize(int newCapacity) {
280         Entry[] oldTable = table;
281         int oldCapacity = oldTable.length;
282         if (oldCapacity == MAXIMUM_CAPACITY) {
283             threshold = Integer.MAX_VALUE;
284             return;
285         }
286
287         Entry[] newTable = new Entry[newCapacity];
288         transfer(newTable);
289         table = newTable;
290         threshold = (int)(newCapacity * loadFactor);
291     }
292
293     /**
294      * Transfer all entries from current table to newTable.
295      */

296     private void transfer(Entry[] newTable) {
297         Entry[] src = table;
298         int newCapacity = newTable.length;
299         for (int j = 0; j < src.length; j++) {
300             Entry e = src[j];
301             if (e != null) {
302                 src[j] = null;
303                 do {
304                     Entry next = e.next;
305                     int i = e.key & (newCapacity - 1);
306                     e.next = newTable[i];
307                     newTable[i] = e;
308                     e = next;
309                 } while (e != null);
310             }
311         }
312     }
313
314     /**
315      * Removes the mapping for this key from this map if present.
316      *
317      * @param key key whose mapping is to be removed from the map.
318      * @return previous value associated with specified key, or <tt>null</tt>
319      * if there was no mapping for key. A <tt>null</tt> return can
320      * also indicate that the map previously associated <tt>null</tt>
321      * with the specified key.
322      */

323     public Object JavaDoc remove(int key) {
324         Entry e = removeEntryForKey(key);
325         return e == null ? e : e.value;
326     }
327
328     /**
329      * Removes and returns the entry associated with the specified key
330      * in the IntObjectHashMap. Returns null if the IntObjectHashMap contains no mapping
331      * for this key.
332      */

333     private Entry removeEntryForKey(int key) {
334         int i = key & (table.length - 1);
335         Entry prev = table[i];
336         Entry e = prev;
337
338         while (e != null) {
339             Entry next = e.next;
340             if (key == e.key) {
341                 size--;
342                 if (prev == e) {
343                     table[i] = next;
344                 } else {
345                     prev.next = next;
346                 }
347                 return e;
348             }
349             prev = e;
350             e = next;
351         }
352
353         return e;
354     }
355
356     /**
357      * Removes all mappings from this map.
358      */

359     public void clear() {
360         Entry tab[] = table;
361         for (int i = 0; i < tab.length; i++) {
362             tab[i] = null;
363         }
364         size = 0;
365     }
366
367     /**
368      * Returns <tt>true</tt> if this map maps one or more keys to the
369      * specified value.
370      *
371      * @param value value whose presence in this map is to be tested.
372      * @return <tt>true</tt> if this map maps one or more keys to the
373      * specified value.
374      */

375     public boolean containsValue(Object JavaDoc value) {
376         Entry tab[] = table;
377         for (int i = 0; i < tab.length; i++) {
378             for (Entry e = tab[i]; e != null; e = e.next) {
379                 if (value.equals(e.value)) {
380                     return true;
381                 }
382             }
383         }
384         return false;
385     }
386
387     private static class Entry {
388
389         final int key;
390         Object JavaDoc value;
391         Entry next;
392
393         /**
394          * Create new entry.
395          */

396         public Entry(int k, Object JavaDoc v, Entry n) {
397             value = v;
398             next = n;
399             key = k;
400         }
401
402         public Object JavaDoc getValue() {
403             return value;
404         }
405
406         public Object JavaDoc setValue(Object JavaDoc newValue) {
407             Object JavaDoc oldValue = value;
408             value = newValue;
409             return oldValue;
410         }
411
412         public boolean equals(Object JavaDoc o) {
413             if (!(o instanceof Entry)) {
414                 return false;
415             }
416             Entry e = (Entry)o;
417             if (key == e.key) {
418                 if (value == e.value || (value != null && value.equals(e.value))) {
419                     return true;
420                 }
421             }
422             return false;
423         }
424
425         public int hashCode() {
426             return key ^ (value == null ? 0 : value.hashCode());
427         }
428
429         public String JavaDoc toString() {
430             return key + "=" + getValue();
431         }
432
433     }
434
435     /**
436      * Add a new entry with the specified key, value and hash code to
437      * the specified bucket. It is the responsibility of this
438      * method to resize the table if appropriate.
439      * <p/>
440      * Subclass overrides this to alter the behavior of put method.
441      */

442     private void addEntry(int key, Object JavaDoc value, int bucketIndex) {
443         table[bucketIndex] = new Entry(key, value, table[bucketIndex]);
444         if (size++ >= threshold) {
445             resize(2 * table.length);
446         }
447     }
448
449     /**
450      * Like addEntry except that this version is used when creating entries
451      * as part of Map construction or "pseudo-construction" (cloning,
452      * deserialization). This version needn't worry about resizing the table.
453      * <p/>
454      * Subclass overrides this to alter the behavior of IntObjectHashMap(Map),
455      * clone, and readObject.
456      */

457     private void createEntry(int key, Object JavaDoc value, int bucketIndex) {
458         table[bucketIndex] = new Entry(key, value, table[bucketIndex]);
459         size++;
460     }
461
462     /**
463      * Save the state of the <tt>IntObjectHashMap</tt> instance to a stream (i.e.,
464      * serialize it).
465      *
466      * @serialData The <i>capacity</i> of the IntObjectHashMap (the length of the
467      * bucket array) is emitted (int), followed by the
468      * <i>size</i> of the IntObjectHashMap (the number of key-value
469      * mappings), followed by the key (Object) and value (Object)
470      * for each key-value mapping represented by the IntObjectHashMap
471      * The key-value mappings are emitted in the order that they
472      * are returned by <tt>entrySet().iterator()</tt>.
473      */

474     private void writeObject(java.io.ObjectOutputStream JavaDoc s)
475             throws IOException JavaDoc {
476         // Write out the threshold, loadfactor, and any hidden stuff
477
s.defaultWriteObject();
478
479         // Write out number of buckets
480
s.writeInt(table.length);
481
482         // Write out size (number of Mappings)
483
s.writeInt(size);
484
485         // Write out keys and values (alternating)
486
int c = 0;
487         for (int i = 0; c < size && i < table.length; i++) {
488             Entry e = table[i];
489             for (; e != null; e = e.next, ++c) {
490                 s.writeInt(e.key);
491                 s.writeObject(e.getValue());
492             }
493         }
494     }
495
496     /**
497      * Reconstitute the <tt>IntObjectHashMap</tt> instance from a stream (i.e.,
498      * deserialize it).
499      */

500     private void readObject(java.io.ObjectInputStream JavaDoc s)
501             throws IOException JavaDoc, ClassNotFoundException JavaDoc {
502         // Read in the threshold, loadfactor, and any hidden stuff
503
s.defaultReadObject();
504
505         // Read in number of buckets and allocate the bucket array;
506
int numBuckets = s.readInt();
507         table = new Entry[numBuckets];
508
509         // Read in size (number of Mappings)
510
int size = s.readInt();
511
512         // Read the keys and values, and put the mappings in the IntObjectHashMap
513
for (int i = 0; i < size; i++) {
514             int key = s.readInt();
515             Object JavaDoc value = s.readObject();
516             putForCreate(key, value);
517         }
518     }
519
520 }
521
Popular Tags