129 /**
130 * The default initial capacity - MUST be a power of two.
131 */
132 static final int DEFAULT_INITIAL_CAPACITY = 16;
133
134 /**
135 * The maximum capacity, used if a higher value is implicitly specified
136 * by either of the constructors with arguments.
137 * MUST be a power of two <= 1<<30.
138 */
139 static final int MAXIMUM_CAPACITY = 1 << 30;
140
141 /**
142 * The load factor used when none specified in constructor.
143 */
144 static final float DEFAULT_LOAD_FACTOR = 0.75f;
145
146 /**
147 * The table, resized as necessary. Length MUST Always be a power of two.
148 */
149 transient Entry[] table;
150
151 /**
152 * The number of key-value mappings contained in this map.
153 */
154 transient int size;
155
156 /**
157 * The next size value at which to resize (capacity * load factor).
158 * @serial
159 */
160 int threshold;
161
162 /**
163 * The load factor for the hash table.
164 *
165 * @serial
166 */
167 final float loadFactor;
168
169 /**
170 * The number of times this HashMap has been structurally modified
171 * Structural modifications are those that change the number of mappings in
172 * the HashMap or otherwise modify its internal structure (e.g.,
173 * rehash). This field is used to make iterators on Collection-views of
174 * the HashMap fail-fast. (See ConcurrentModificationException).
175 */
176 transient int modCount;
177
178 /**
179 * Constructs an empty <tt>HashMap</tt> with the specified initial
180 * capacity and load factor.
181 *
182 * @param initialCapacity the initial capacity
183 * @param loadFactor the load factor
184 * @throws IllegalArgumentException if the initial capacity is negative
185 * or the load factor is nonpositive
186 */
187 public HashMap(int initialCapacity, float loadFactor) {
188 if (initialCapacity < 0)
189 throw new IllegalArgumentException("Illegal initial capacity: " +
190 initialCapacity);
191 if (initialCapacity > MAXIMUM_CAPACITY)
192 initialCapacity = MAXIMUM_CAPACITY;
193 if (loadFactor <= 0 || Float.isNaN(loadFactor))
194 throw new IllegalArgumentException("Illegal load factor: " +
195 loadFactor);
196
197 // Find a power of 2 >= initialCapacity
198 int capacity = 1;
199 while (capacity < initialCapacity)
200 capacity <<= 1;
201
202 this.loadFactor = loadFactor;
203 threshold = (int)(capacity * loadFactor);
204 table = new Entry[capacity];
205 init();
206 }
207
208 /**
209 * Constructs an empty <tt>HashMap</tt> with the specified initial
210 * capacity and the default load factor (0.75).
211 *
212 * @param initialCapacity the initial capacity.
213 * @throws IllegalArgumentException if the initial capacity is negative.
214 */
215 public HashMap(int initialCapacity) {
216 this(initialCapacity, DEFAULT_LOAD_FACTOR);
217 }
218
219 /**
220 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
221 * (16) and the default load factor (0.75).
222 */
223 public HashMap() {
224 this.loadFactor = DEFAULT_LOAD_FACTOR;
225 threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
226 table = new Entry[DEFAULT_INITIAL_CAPACITY];
227 init();
228 }
229
230 /**
231 * Constructs a new <tt>HashMap</tt> with the same mappings as the
232 * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
233 * default load factor (0.75) and an initial capacity sufficient to
234 * hold the mappings in the specified <tt>Map</tt>.
235 *
236 * @param m the map whose mappings are to be placed in this map
237 * @throws NullPointerException if the specified map is null
238 */
239 public HashMap(Map<? extends K, ? extends V> m) {
240 this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
241 DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
242 putAllForCreate(m);
243 }
244
245 // internal utilities
246
247 /**
248 * Initialization hook for subclasses. This method is called
249 * in all constructors and pseudo-constructors (clone, readObject)
250 * after HashMap has been initialized but before any entries have
251 * been inserted. (In the absence of this method, readObject would
252 * require explicit knowledge of subclasses.)
253 */
254 void init() {
255 }
256
257 /**
258 * Applies a supplemental hash function to a given hashCode, which
259 * defends against poor quality hash functions. This is critical
260 * because HashMap uses power-of-two length hash tables, that
261 * otherwise encounter collisions for hashCodes that do not differ
262 * in lower bits. Note: Null keys always map to hash 0, thus index 0.
263 */
264 static int hash(int h) {
265 // This function ensures that hashCodes that differ only by
266 // constant multiples at each bit position have a bounded
267 // number of collisions (approximately 8 at default load factor).
268 h ^= (h >>> 20) ^ (h >>> 12);
269 return h ^ (h >>> 7) ^ (h >>> 4);
270 }
271
272 /**
273 * Returns index for hash code h.
274 */
275 static int indexFor(int h, int length) {
276 return h & (length-1);
277 }
278
279 /**
280 * Returns the number of key-value mappings in this map.
281 *
282 * @return the number of key-value mappings in this map
283 */
284 public int size() {
297 /**
298 * Returns the value to which the specified key is mapped,
299 * or {@code null} if this map contains no mapping for the key.
300 *
301 * <p>More formally, if this map contains a mapping from a key
302 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
303 * key.equals(k))}, then this method returns {@code v}; otherwise
304 * it returns {@code null}. (There can be at most one such mapping.)
305 *
306 * <p>A return value of {@code null} does not <i>necessarily</i>
307 * indicate that the map contains no mapping for the key; it's also
308 * possible that the map explicitly maps the key to {@code null}.
309 * The {@link #containsKey containsKey} operation may be used to
310 * distinguish these two cases.
311 *
312 * @see #put(Object, Object)
313 */
314 public V get(Object key) {
315 if (key == null)
316 return getForNullKey();
317 int hash = hash(key.hashCode());
318 for (Entry<K,V> e = table[indexFor(hash, table.length)];
319 e != null;
320 e = e.next) {
321 Object k;
322 if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
323 return e.value;
324 }
325 return null;
326 }
327
328 /**
329 * Offloaded version of get() to look up null keys. Null keys map
330 * to index 0. This null case is split out into separate methods
331 * for the sake of performance in the two most commonly used
332 * operations (get and put), but incorporated with conditionals in
333 * others.
334 */
335 private V getForNullKey() {
336 for (Entry<K,V> e = table[0]; e != null; e = e.next) {
337 if (e.key == null)
338 return e.value;
339 }
340 return null;
341 }
342
343 /**
344 * Returns <tt>true</tt> if this map contains a mapping for the
345 * specified key.
346 *
347 * @param key The key whose presence in this map is to be tested
348 * @return <tt>true</tt> if this map contains a mapping for the specified
349 * key.
350 */
351 public boolean containsKey(Object key) {
352 return getEntry(key) != null;
353 }
354
355 /**
356 * Returns the entry associated with the specified key in the
357 * HashMap. Returns null if the HashMap contains no mapping
358 * for the key.
359 */
360 final Entry<K,V> getEntry(Object key) {
361 int hash = (key == null) ? 0 : hash(key.hashCode());
362 for (Entry<K,V> e = table[indexFor(hash, table.length)];
363 e != null;
364 e = e.next) {
365 Object k;
366 if (e.hash == hash &&
367 ((k = e.key) == key || (key != null && key.equals(k))))
368 return e;
369 }
370 return null;
371 }
372
373
374 /**
375 * Associates the specified value with the specified key in this map.
376 * If the map previously contained a mapping for the key, the old
377 * value is replaced.
378 *
379 * @param key key with which the specified value is to be associated
380 * @param value value to be associated with the specified key
381 * @return the previous value associated with <tt>key</tt>, or
382 * <tt>null</tt> if there was no mapping for <tt>key</tt>.
383 * (A <tt>null</tt> return can also indicate that the map
384 * previously associated <tt>null</tt> with <tt>key</tt>.)
385 */
386 public V put(K key, V value) {
387 if (key == null)
388 return putForNullKey(value);
389 int hash = hash(key.hashCode());
390 int i = indexFor(hash, table.length);
391 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
392 Object k;
393 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
394 V oldValue = e.value;
395 e.value = value;
396 e.recordAccess(this);
397 return oldValue;
398 }
399 }
400
401 modCount++;
402 addEntry(hash, key, value, i);
403 return null;
404 }
405
406 /**
407 * Offloaded version of put for null keys
408 */
409 private V putForNullKey(V value) {
410 for (Entry<K,V> e = table[0]; e != null; e = e.next) {
411 if (e.key == null) {
412 V oldValue = e.value;
413 e.value = value;
414 e.recordAccess(this);
415 return oldValue;
416 }
417 }
418 modCount++;
419 addEntry(0, null, value, 0);
420 return null;
421 }
422
423 /**
424 * This method is used instead of put by constructors and
425 * pseudoconstructors (clone, readObject). It does not resize the table,
426 * check for comodification, etc. It calls createEntry rather than
427 * addEntry.
428 */
429 private void putForCreate(K key, V value) {
430 int hash = (key == null) ? 0 : hash(key.hashCode());
431 int i = indexFor(hash, table.length);
432
433 /**
434 * Look for preexisting entry for key. This will never happen for
435 * clone or deserialize. It will only happen for construction if the
436 * input Map is a sorted map whose ordering is inconsistent w/ equals.
437 */
438 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
439 Object k;
440 if (e.hash == hash &&
441 ((k = e.key) == key || (key != null && key.equals(k)))) {
442 e.value = value;
443 return;
444 }
445 }
446
447 createEntry(hash, key, value, i);
448 }
449
450 private void putAllForCreate(Map<? extends K, ? extends V> m) {
458 * number of keys in this map reaches its threshold.
459 *
460 * If current capacity is MAXIMUM_CAPACITY, this method does not
461 * resize the map, but sets threshold to Integer.MAX_VALUE.
462 * This has the effect of preventing future calls.
463 *
464 * @param newCapacity the new capacity, MUST be a power of two;
465 * must be greater than current capacity unless current
466 * capacity is MAXIMUM_CAPACITY (in which case value
467 * is irrelevant).
468 */
469 void resize(int newCapacity) {
470 Entry[] oldTable = table;
471 int oldCapacity = oldTable.length;
472 if (oldCapacity == MAXIMUM_CAPACITY) {
473 threshold = Integer.MAX_VALUE;
474 return;
475 }
476
477 Entry[] newTable = new Entry[newCapacity];
478 transfer(newTable);
479 table = newTable;
480 threshold = (int)(newCapacity * loadFactor);
481 }
482
483 /**
484 * Transfers all entries from current table to newTable.
485 */
486 void transfer(Entry[] newTable) {
487 Entry[] src = table;
488 int newCapacity = newTable.length;
489 for (int j = 0; j < src.length; j++) {
490 Entry<K,V> e = src[j];
491 if (e != null) {
492 src[j] = null;
493 do {
494 Entry<K,V> next = e.next;
495 int i = indexFor(e.hash, newCapacity);
496 e.next = newTable[i];
497 newTable[i] = e;
498 e = next;
499 } while (e != null);
500 }
501 }
502 }
503
504 /**
505 * Copies all of the mappings from the specified map to this map.
506 * These mappings will replace any mappings that this map had for
507 * any of the keys currently in the specified map.
508 *
509 * @param m mappings to be stored in this map
510 * @throws NullPointerException if the specified map is null
511 */
512 public void putAll(Map<? extends K, ? extends V> m) {
513 int numKeysToBeAdded = m.size();
514 if (numKeysToBeAdded == 0)
515 return;
516
517 /*
518 * Expand the map if the map if the number of mappings to be added
519 * is greater than or equal to threshold. This is conservative; the
541 /**
542 * Removes the mapping for the specified key from this map if present.
543 *
544 * @param key key whose mapping is to be removed from the map
545 * @return the previous value associated with <tt>key</tt>, or
546 * <tt>null</tt> if there was no mapping for <tt>key</tt>.
547 * (A <tt>null</tt> return can also indicate that the map
548 * previously associated <tt>null</tt> with <tt>key</tt>.)
549 */
550 public V remove(Object key) {
551 Entry<K,V> e = removeEntryForKey(key);
552 return (e == null ? null : e.value);
553 }
554
555 /**
556 * Removes and returns the entry associated with the specified key
557 * in the HashMap. Returns null if the HashMap contains no mapping
558 * for this key.
559 */
560 final Entry<K,V> removeEntryForKey(Object key) {
561 int hash = (key == null) ? 0 : hash(key.hashCode());
562 int i = indexFor(hash, table.length);
563 Entry<K,V> prev = table[i];
564 Entry<K,V> e = prev;
565
566 while (e != null) {
567 Entry<K,V> next = e.next;
568 Object k;
569 if (e.hash == hash &&
570 ((k = e.key) == key || (key != null && key.equals(k)))) {
571 modCount++;
572 size--;
573 if (prev == e)
574 table[i] = next;
575 else
576 prev.next = next;
577 e.recordRemoval(this);
578 return e;
579 }
580 prev = e;
581 e = next;
582 }
583
584 return e;
585 }
586
587 /**
588 * Special version of remove for EntrySet.
589 */
590 final Entry<K,V> removeMapping(Object o) {
591 if (!(o instanceof Map.Entry))
592 return null;
593
594 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
595 Object key = entry.getKey();
596 int hash = (key == null) ? 0 : hash(key.hashCode());
597 int i = indexFor(hash, table.length);
598 Entry<K,V> prev = table[i];
599 Entry<K,V> e = prev;
600
601 while (e != null) {
602 Entry<K,V> next = e.next;
603 if (e.hash == hash && e.equals(entry)) {
604 modCount++;
605 size--;
606 if (prev == e)
607 table[i] = next;
608 else
671 HashMap<K,V> result = null;
672 try {
673 result = (HashMap<K,V>)super.clone();
674 } catch (CloneNotSupportedException e) {
675 // assert false;
676 }
677 result.table = new Entry[table.length];
678 result.entrySet = null;
679 result.modCount = 0;
680 result.size = 0;
681 result.init();
682 result.putAllForCreate(this);
683
684 return result;
685 }
686
687 static class Entry<K,V> implements Map.Entry<K,V> {
688 final K key;
689 V value;
690 Entry<K,V> next;
691 final int hash;
692
693 /**
694 * Creates new entry.
695 */
696 Entry(int h, K k, V v, Entry<K,V> n) {
697 value = v;
698 next = n;
699 key = k;
700 hash = h;
701 }
702
703 public final K getKey() {
704 return key;
705 }
706
707 public final V getValue() {
708 return value;
709 }
710
711 public final V setValue(V newValue) {
745 */
746 void recordAccess(HashMap<K,V> m) {
747 }
748
749 /**
750 * This method is invoked whenever the entry is
751 * removed from the table.
752 */
753 void recordRemoval(HashMap<K,V> m) {
754 }
755 }
756
757 /**
758 * Adds a new entry with the specified key, value and hash code to
759 * the specified bucket. It is the responsibility of this
760 * method to resize the table if appropriate.
761 *
762 * Subclass overrides this to alter the behavior of put method.
763 */
764 void addEntry(int hash, K key, V value, int bucketIndex) {
765 Entry<K,V> e = table[bucketIndex];
766 table[bucketIndex] = new Entry<>(hash, key, value, e);
767 if (size++ >= threshold)
768 resize(2 * table.length);
769 }
770
771 /**
772 * Like addEntry except that this version is used when creating entries
773 * as part of Map construction or "pseudo-construction" (cloning,
774 * deserialization). This version needn't worry about resizing the table.
775 *
776 * Subclass overrides this to alter the behavior of HashMap(Map),
777 * clone, and readObject.
778 */
779 void createEntry(int hash, K key, V value, int bucketIndex) {
780 Entry<K,V> e = table[bucketIndex];
781 table[bucketIndex] = new Entry<>(hash, key, value, e);
782 size++;
783 }
784
785 private abstract class HashIterator<E> implements Iterator<E> {
786 Entry<K,V> next; // next entry to return
787 int expectedModCount; // For fast-fail
788 int index; // current slot
810
811 if ((next = e.next) == null) {
812 Entry[] t = table;
813 while (index < t.length && (next = t[index++]) == null)
814 ;
815 }
816 current = e;
817 return e;
818 }
819
820 public void remove() {
821 if (current == null)
822 throw new IllegalStateException();
823 if (modCount != expectedModCount)
824 throw new ConcurrentModificationException();
825 Object k = current.key;
826 current = null;
827 HashMap.this.removeEntryForKey(k);
828 expectedModCount = modCount;
829 }
830
831 }
832
833 private final class ValueIterator extends HashIterator<V> {
834 public V next() {
835 return nextEntry().value;
836 }
837 }
838
839 private final class KeyIterator extends HashIterator<K> {
840 public K next() {
841 return nextEntry().getKey();
842 }
843 }
844
845 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
846 public Map.Entry<K,V> next() {
847 return nextEntry();
848 }
849 }
850
990 * mappings), followed by the key (Object) and value (Object)
991 * for each key-value mapping. The key-value mappings are
992 * emitted in no particular order.
993 */
994 private void writeObject(java.io.ObjectOutputStream s)
995 throws IOException
996 {
997 Iterator<Map.Entry<K,V>> i =
998 (size > 0) ? entrySet0().iterator() : null;
999
1000 // Write out the threshold, loadfactor, and any hidden stuff
1001 s.defaultWriteObject();
1002
1003 // Write out number of buckets
1004 s.writeInt(table.length);
1005
1006 // Write out size (number of Mappings)
1007 s.writeInt(size);
1008
1009 // Write out keys and values (alternating)
1010 if (i != null) {
1011 while (i.hasNext()) {
1012 Map.Entry<K,V> e = i.next();
1013 s.writeObject(e.getKey());
1014 s.writeObject(e.getValue());
1015 }
1016 }
1017 }
1018
1019 private static final long serialVersionUID = 362498820763181265L;
1020
1021 /**
1022 * Reconstitute the <tt>HashMap</tt> instance from a stream (i.e.,
1023 * deserialize it).
1024 */
1025 private void readObject(java.io.ObjectInputStream s)
1026 throws IOException, ClassNotFoundException
1027 {
1028 // Read in the threshold, loadfactor, and any hidden stuff
1029 s.defaultReadObject();
1030
1031 // Read in number of buckets and allocate the bucket array;
1032 int numBuckets = s.readInt();
1033 table = new Entry[numBuckets];
1034
1035 init(); // Give subclass a chance to do its thing.
1036
1037 // Read in size (number of Mappings)
1038 int size = s.readInt();
1039
1040 // Read the keys and values, and put the mappings in the HashMap
1041 for (int i=0; i<size; i++) {
1042 K key = (K) s.readObject();
1043 V value = (V) s.readObject();
1044 putForCreate(key, value);
1045 }
1046 }
1047
1048 // These methods are used when serializing HashSets
1049 int capacity() { return table.length; }
1050 float loadFactor() { return loadFactor; }
1051 }
|
129 /**
130 * The default initial capacity - MUST be a power of two.
131 */
132 static final int DEFAULT_INITIAL_CAPACITY = 16;
133
134 /**
135 * The maximum capacity, used if a higher value is implicitly specified
136 * by either of the constructors with arguments.
137 * MUST be a power of two <= 1<<30.
138 */
139 static final int MAXIMUM_CAPACITY = 1 << 30;
140
141 /**
142 * The load factor used when none specified in constructor.
143 */
144 static final float DEFAULT_LOAD_FACTOR = 0.75f;
145
146 /**
147 * The table, resized as necessary. Length MUST Always be a power of two.
148 */
149 transient Entry<K,V>[] table;
150
151 /**
152 * The number of key-value mappings contained in this map.
153 */
154 transient int size;
155
156 /**
157 * The next size value at which to resize (capacity * load factor).
158 * @serial
159 */
160 int threshold;
161
162 /**
163 * The load factor for the hash table.
164 *
165 * @serial
166 */
167 final float loadFactor;
168
169 /**
170 * The number of times this HashMap has been structurally modified
171 * Structural modifications are those that change the number of mappings in
172 * the HashMap or otherwise modify its internal structure (e.g.,
173 * rehash). This field is used to make iterators on Collection-views of
174 * the HashMap fail-fast. (See ConcurrentModificationException).
175 */
176 transient int modCount;
177
178 /**
179 * The default threshold of capacity above which alternate hashing is used.
180 * Alternative hashing reduces the incidence of collisions due to weak hash
181 * code calculation.
182 * <p/>
183 * This value may be overridden by defining the system property
184 * {@code java.util.althashing.threshold}. A property value of {@code 1}
185 * forces alternative hashing to be used at all times whereas
186 * {@code 2147483648 } ({@code Integer.MAX_VALUE}) value ensures that
187 * alternative hashing is never used.
188 */
189 static final int ALTERNATE_HASHING_THRESHOLD_DEFAULT = 0;
190
191 /**
192 * holds values which can't be initialized until after VM is booted.
193 */
194 private static class Holder {
195
196 // Unsafe mechanics
197 /**
198 *
199 */
200 static final sun.misc.Unsafe UNSAFE;
201
202 /**
203 * Offset of "final" hashmask field we must set in
204 * readObject() method.
205 */
206 static final long HASHSEED_OFFSET;
207
208 /**
209 * Table capacity above which to switch to use alternate hashing.
210 */
211 static final int ALTERNATE_HASHING_THRESHOLD;
212
213 static {
214 String altThreshold = java.security.AccessController.doPrivileged(
215 new sun.security.action.GetPropertyAction(
216 "jdk.map.althashing.threshold"));
217
218 int threshold;
219 try {
220 threshold = (null != altThreshold)
221 ? Integer.parseInt(altThreshold)
222 : ALTERNATE_HASHING_THRESHOLD_DEFAULT;
223
224 if(threshold == -1) {
225 threshold = Integer.MAX_VALUE;
226 }
227
228 if(threshold < 0) {
229 throw new IllegalArgumentException("value must be positive integer.");
230 }
231 } catch(IllegalArgumentException failed) {
232 throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
233 }
234 ALTERNATE_HASHING_THRESHOLD = threshold;
235
236 try {
237 UNSAFE = sun.misc.Unsafe.getUnsafe();
238 HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
239 HashMap.class.getDeclaredField("hashSeed"));
240 } catch (NoSuchFieldException | SecurityException e) {
241 throw new Error("Failed to record hashSeed offset", e);
242 }
243 }
244 }
245
246 /**
247 * If {@code true} then perform alternate hashing to reduce the incidence of
248 * collisions due to weak hash code calculation.
249 */
250 transient boolean useAltHashing;
251
252 /**
253 * A randomizing value associated with this instance that is applied to
254 * hash code of keys to make hash collisions harder to find.
255 */
256 transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
257
258 /**
259 * Constructs an empty <tt>HashMap</tt> with the specified initial
260 * capacity and load factor.
261 *
262 * @param initialCapacity the initial capacity
263 * @param loadFactor the load factor
264 * @throws IllegalArgumentException if the initial capacity is negative
265 * or the load factor is nonpositive
266 */
267 public HashMap(int initialCapacity, float loadFactor) {
268 if (initialCapacity < 0)
269 throw new IllegalArgumentException("Illegal initial capacity: " +
270 initialCapacity);
271 if (initialCapacity > MAXIMUM_CAPACITY)
272 initialCapacity = MAXIMUM_CAPACITY;
273 if (loadFactor <= 0 || Float.isNaN(loadFactor))
274 throw new IllegalArgumentException("Illegal load factor: " +
275 loadFactor);
276
277 // Find a power of 2 >= initialCapacity
278 int capacity = 1;
279 while (capacity < initialCapacity)
280 capacity <<= 1;
281
282 this.loadFactor = loadFactor;
283 threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
284 table = new Entry[capacity];
285 useAltHashing = sun.misc.VM.isBooted() &&
286 (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
287 init();
288 }
289
290 /**
291 * Constructs an empty <tt>HashMap</tt> with the specified initial
292 * capacity and the default load factor (0.75).
293 *
294 * @param initialCapacity the initial capacity.
295 * @throws IllegalArgumentException if the initial capacity is negative.
296 */
297 public HashMap(int initialCapacity) {
298 this(initialCapacity, DEFAULT_LOAD_FACTOR);
299 }
300
301 /**
302 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
303 * (16) and the default load factor (0.75).
304 */
305 public HashMap() {
306 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
307 }
308
309 /**
310 * Constructs a new <tt>HashMap</tt> with the same mappings as the
311 * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
312 * default load factor (0.75) and an initial capacity sufficient to
313 * hold the mappings in the specified <tt>Map</tt>.
314 *
315 * @param m the map whose mappings are to be placed in this map
316 * @throws NullPointerException if the specified map is null
317 */
318 public HashMap(Map<? extends K, ? extends V> m) {
319 this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
320 DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
321 putAllForCreate(m);
322 }
323
324 // internal utilities
325
326 /**
327 * Initialization hook for subclasses. This method is called
328 * in all constructors and pseudo-constructors (clone, readObject)
329 * after HashMap has been initialized but before any entries have
330 * been inserted. (In the absence of this method, readObject would
331 * require explicit knowledge of subclasses.)
332 */
333 void init() {
334 }
335
336 /**
337 * Retrieve object hash code and applies a supplemental hash function to the
338 * result hash, which defends against poor quality hash functions. This is
339 * critical because HashMap uses power-of-two length hash tables, that
340 * otherwise encounter collisions for hashCodes that do not differ
341 * in lower bits. Note: Null keys always map to hash 0, thus index 0.
342 */
343 final int hash(Object k) {
344 int h = 0;
345 if (useAltHashing) {
346 if (k instanceof String) {
347 return sun.misc.Hashing.stringHash32((String) k);
348 }
349 h = hashSeed;
350 }
351
352 h ^= k.hashCode();
353
354 // This function ensures that hashCodes that differ only by
355 // constant multiples at each bit position have a bounded
356 // number of collisions (approximately 8 at default load factor).
357 h ^= (h >>> 20) ^ (h >>> 12);
358 return h ^ (h >>> 7) ^ (h >>> 4);
359 }
360
361 /**
362 * Returns index for hash code h.
363 */
364 static int indexFor(int h, int length) {
365 return h & (length-1);
366 }
367
368 /**
369 * Returns the number of key-value mappings in this map.
370 *
371 * @return the number of key-value mappings in this map
372 */
373 public int size() {
386 /**
387 * Returns the value to which the specified key is mapped,
388 * or {@code null} if this map contains no mapping for the key.
389 *
390 * <p>More formally, if this map contains a mapping from a key
391 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
392 * key.equals(k))}, then this method returns {@code v}; otherwise
393 * it returns {@code null}. (There can be at most one such mapping.)
394 *
395 * <p>A return value of {@code null} does not <i>necessarily</i>
396 * indicate that the map contains no mapping for the key; it's also
397 * possible that the map explicitly maps the key to {@code null}.
398 * The {@link #containsKey containsKey} operation may be used to
399 * distinguish these two cases.
400 *
401 * @see #put(Object, Object)
402 */
403 public V get(Object key) {
404 if (key == null)
405 return getForNullKey();
406 Entry<K,V> entry = getEntry(key);
407
408 return null == entry ? null : entry.getValue();
409 }
410
411 /**
412 * Offloaded version of get() to look up null keys. Null keys map
413 * to index 0. This null case is split out into separate methods
414 * for the sake of performance in the two most commonly used
415 * operations (get and put), but incorporated with conditionals in
416 * others.
417 */
418 private V getForNullKey() {
419 for (Entry<K,V> e = table[0]; e != null; e = e.next) {
420 if (e.key == null)
421 return e.value;
422 }
423 return null;
424 }
425
426 /**
427 * Returns <tt>true</tt> if this map contains a mapping for the
428 * specified key.
429 *
430 * @param key The key whose presence in this map is to be tested
431 * @return <tt>true</tt> if this map contains a mapping for the specified
432 * key.
433 */
434 public boolean containsKey(Object key) {
435 return getEntry(key) != null;
436 }
437
438 /**
439 * Returns the entry associated with the specified key in the
440 * HashMap. Returns null if the HashMap contains no mapping
441 * for the key.
442 */
443 final Entry<K,V> getEntry(Object key) {
444 int hash = (key == null) ? 0 : hash(key);
445 for (Entry<K,V> e = table[indexFor(hash, table.length)];
446 e != null;
447 e = e.next) {
448 Object k;
449 if (e.hash == hash &&
450 ((k = e.key) == key || (key != null && key.equals(k))))
451 return e;
452 }
453 return null;
454 }
455
456
457 /**
458 * Associates the specified value with the specified key in this map.
459 * If the map previously contained a mapping for the key, the old
460 * value is replaced.
461 *
462 * @param key key with which the specified value is to be associated
463 * @param value value to be associated with the specified key
464 * @return the previous value associated with <tt>key</tt>, or
465 * <tt>null</tt> if there was no mapping for <tt>key</tt>.
466 * (A <tt>null</tt> return can also indicate that the map
467 * previously associated <tt>null</tt> with <tt>key</tt>.)
468 */
469 public V put(K key, V value) {
470 if (key == null)
471 return putForNullKey(value);
472 int hash = hash(key);
473 int i = indexFor(hash, table.length);
474 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
475 Object k;
476 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
477 V oldValue = e.value;
478 e.value = value;
479 e.recordAccess(this);
480 return oldValue;
481 }
482 }
483
484 modCount++;
485 addEntry(hash, key, value, i);
486 return null;
487 }
488
489 /**
490 * Offloaded version of put for null keys
491 */
492 private V putForNullKey(V value) {
493 for (Entry<K,V> e = table[0]; e != null; e = e.next) {
494 if (e.key == null) {
495 V oldValue = e.value;
496 e.value = value;
497 e.recordAccess(this);
498 return oldValue;
499 }
500 }
501 modCount++;
502 addEntry(0, null, value, 0);
503 return null;
504 }
505
506 /**
507 * This method is used instead of put by constructors and
508 * pseudoconstructors (clone, readObject). It does not resize the table,
509 * check for comodification, etc. It calls createEntry rather than
510 * addEntry.
511 */
512 private void putForCreate(K key, V value) {
513 int hash = null == key ? 0 : hash(key);
514 int i = indexFor(hash, table.length);
515
516 /**
517 * Look for preexisting entry for key. This will never happen for
518 * clone or deserialize. It will only happen for construction if the
519 * input Map is a sorted map whose ordering is inconsistent w/ equals.
520 */
521 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
522 Object k;
523 if (e.hash == hash &&
524 ((k = e.key) == key || (key != null && key.equals(k)))) {
525 e.value = value;
526 return;
527 }
528 }
529
530 createEntry(hash, key, value, i);
531 }
532
533 private void putAllForCreate(Map<? extends K, ? extends V> m) {
541 * number of keys in this map reaches its threshold.
542 *
543 * If current capacity is MAXIMUM_CAPACITY, this method does not
544 * resize the map, but sets threshold to Integer.MAX_VALUE.
545 * This has the effect of preventing future calls.
546 *
547 * @param newCapacity the new capacity, MUST be a power of two;
548 * must be greater than current capacity unless current
549 * capacity is MAXIMUM_CAPACITY (in which case value
550 * is irrelevant).
551 */
552 void resize(int newCapacity) {
553 Entry[] oldTable = table;
554 int oldCapacity = oldTable.length;
555 if (oldCapacity == MAXIMUM_CAPACITY) {
556 threshold = Integer.MAX_VALUE;
557 return;
558 }
559
560 Entry[] newTable = new Entry[newCapacity];
561 boolean oldAltHashing = useAltHashing;
562 useAltHashing |= sun.misc.VM.isBooted() &&
563 (newCapacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
564 boolean rehash = oldAltHashing ^ useAltHashing;
565 transfer(newTable, rehash);
566 table = newTable;
567 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
568 }
569
570 /**
571 * Transfers all entries from current table to newTable.
572 */
573 void transfer(Entry[] newTable, boolean rehash) {
574 int newCapacity = newTable.length;
575 for (Entry<K,V> e : table) {
576 while(null != e) {
577 Entry<K,V> next = e.next;
578 if(rehash) {
579 e.hash = null == e.key ? 0 : hash(e.key);
580 }
581 int i = indexFor(e.hash, newCapacity);
582 e.next = newTable[i];
583 newTable[i] = e;
584 e = next;
585 }
586 }
587 }
588
589 /**
590 * Copies all of the mappings from the specified map to this map.
591 * These mappings will replace any mappings that this map had for
592 * any of the keys currently in the specified map.
593 *
594 * @param m mappings to be stored in this map
595 * @throws NullPointerException if the specified map is null
596 */
597 public void putAll(Map<? extends K, ? extends V> m) {
598 int numKeysToBeAdded = m.size();
599 if (numKeysToBeAdded == 0)
600 return;
601
602 /*
603 * Expand the map if the map if the number of mappings to be added
604 * is greater than or equal to threshold. This is conservative; the
626 /**
627 * Removes the mapping for the specified key from this map if present.
628 *
629 * @param key key whose mapping is to be removed from the map
630 * @return the previous value associated with <tt>key</tt>, or
631 * <tt>null</tt> if there was no mapping for <tt>key</tt>.
632 * (A <tt>null</tt> return can also indicate that the map
633 * previously associated <tt>null</tt> with <tt>key</tt>.)
634 */
635 public V remove(Object key) {
636 Entry<K,V> e = removeEntryForKey(key);
637 return (e == null ? null : e.value);
638 }
639
640 /**
641 * Removes and returns the entry associated with the specified key
642 * in the HashMap. Returns null if the HashMap contains no mapping
643 * for this key.
644 */
645 final Entry<K,V> removeEntryForKey(Object key) {
646 int hash = (key == null) ? 0 : hash(key);
647 int i = indexFor(hash, table.length);
648 Entry<K,V> prev = table[i];
649 Entry<K,V> e = prev;
650
651 while (e != null) {
652 Entry<K,V> next = e.next;
653 Object k;
654 if (e.hash == hash &&
655 ((k = e.key) == key || (key != null && key.equals(k)))) {
656 modCount++;
657 size--;
658 if (prev == e)
659 table[i] = next;
660 else
661 prev.next = next;
662 e.recordRemoval(this);
663 return e;
664 }
665 prev = e;
666 e = next;
667 }
668
669 return e;
670 }
671
672 /**
673 * Special version of remove for EntrySet using {@code Map.Entry.equals()}
674 * for matching.
675 */
676 final Entry<K,V> removeMapping(Object o) {
677 if (!(o instanceof Map.Entry))
678 return null;
679
680 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
681 Object key = entry.getKey();
682 int hash = (key == null) ? 0 : hash(key.hashCode());
683 int i = indexFor(hash, table.length);
684 Entry<K,V> prev = table[i];
685 Entry<K,V> e = prev;
686
687 while (e != null) {
688 Entry<K,V> next = e.next;
689 if (e.hash == hash && e.equals(entry)) {
690 modCount++;
691 size--;
692 if (prev == e)
693 table[i] = next;
694 else
757 HashMap<K,V> result = null;
758 try {
759 result = (HashMap<K,V>)super.clone();
760 } catch (CloneNotSupportedException e) {
761 // assert false;
762 }
763 result.table = new Entry[table.length];
764 result.entrySet = null;
765 result.modCount = 0;
766 result.size = 0;
767 result.init();
768 result.putAllForCreate(this);
769
770 return result;
771 }
772
773 static class Entry<K,V> implements Map.Entry<K,V> {
774 final K key;
775 V value;
776 Entry<K,V> next;
777 int hash;
778
779 /**
780 * Creates new entry.
781 */
782 Entry(int h, K k, V v, Entry<K,V> n) {
783 value = v;
784 next = n;
785 key = k;
786 hash = h;
787 }
788
789 public final K getKey() {
790 return key;
791 }
792
793 public final V getValue() {
794 return value;
795 }
796
797 public final V setValue(V newValue) {
831 */
832 void recordAccess(HashMap<K,V> m) {
833 }
834
835 /**
836 * This method is invoked whenever the entry is
837 * removed from the table.
838 */
839 void recordRemoval(HashMap<K,V> m) {
840 }
841 }
842
843 /**
844 * Adds a new entry with the specified key, value and hash code to
845 * the specified bucket. It is the responsibility of this
846 * method to resize the table if appropriate.
847 *
848 * Subclass overrides this to alter the behavior of put method.
849 */
850 void addEntry(int hash, K key, V value, int bucketIndex) {
851 if ((size >= threshold) && (null != table[bucketIndex])) {
852 resize(2 * table.length);
853 hash = hash(key);
854 bucketIndex = indexFor(hash, table.length);
855 }
856
857 createEntry(hash, key, value, bucketIndex);
858 }
859
860 /**
861 * Like addEntry except that this version is used when creating entries
862 * as part of Map construction or "pseudo-construction" (cloning,
863 * deserialization). This version needn't worry about resizing the table.
864 *
865 * Subclass overrides this to alter the behavior of HashMap(Map),
866 * clone, and readObject.
867 */
868 void createEntry(int hash, K key, V value, int bucketIndex) {
869 Entry<K,V> e = table[bucketIndex];
870 table[bucketIndex] = new Entry<>(hash, key, value, e);
871 size++;
872 }
873
874 private abstract class HashIterator<E> implements Iterator<E> {
875 Entry<K,V> next; // next entry to return
876 int expectedModCount; // For fast-fail
877 int index; // current slot
899
900 if ((next = e.next) == null) {
901 Entry[] t = table;
902 while (index < t.length && (next = t[index++]) == null)
903 ;
904 }
905 current = e;
906 return e;
907 }
908
909 public void remove() {
910 if (current == null)
911 throw new IllegalStateException();
912 if (modCount != expectedModCount)
913 throw new ConcurrentModificationException();
914 Object k = current.key;
915 current = null;
916 HashMap.this.removeEntryForKey(k);
917 expectedModCount = modCount;
918 }
919 }
920
921 private final class ValueIterator extends HashIterator<V> {
922 public V next() {
923 return nextEntry().value;
924 }
925 }
926
927 private final class KeyIterator extends HashIterator<K> {
928 public K next() {
929 return nextEntry().getKey();
930 }
931 }
932
933 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
934 public Map.Entry<K,V> next() {
935 return nextEntry();
936 }
937 }
938
1078 * mappings), followed by the key (Object) and value (Object)
1079 * for each key-value mapping. The key-value mappings are
1080 * emitted in no particular order.
1081 */
1082 private void writeObject(java.io.ObjectOutputStream s)
1083 throws IOException
1084 {
1085 Iterator<Map.Entry<K,V>> i =
1086 (size > 0) ? entrySet0().iterator() : null;
1087
1088 // Write out the threshold, loadfactor, and any hidden stuff
1089 s.defaultWriteObject();
1090
1091 // Write out number of buckets
1092 s.writeInt(table.length);
1093
1094 // Write out size (number of Mappings)
1095 s.writeInt(size);
1096
1097 // Write out keys and values (alternating)
1098 if (size > 0) {
1099 for(Map.Entry<K,V> e : entrySet0()) {
1100 s.writeObject(e.getKey());
1101 s.writeObject(e.getValue());
1102 }
1103 }
1104 }
1105
1106 private static final long serialVersionUID = 362498820763181265L;
1107
1108 /**
1109 * Reconstitute the {@code HashMap} instance from a stream (i.e.,
1110 * deserialize it).
1111 */
1112 private void readObject(java.io.ObjectInputStream s)
1113 throws IOException, ClassNotFoundException
1114 {
1115 // Read in the threshold (ignored), loadfactor, and any hidden stuff
1116 s.defaultReadObject();
1117 if (loadFactor <= 0 || Float.isNaN(loadFactor))
1118 throw new InvalidObjectException("Illegal load factor: " +
1119 loadFactor);
1120
1121 // set hashSeed (can only happen after VM boot)
1122 Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
1123 sun.misc.Hashing.randomHashSeed(this));
1124
1125 // Read in number of buckets and allocate the bucket array;
1126 s.readInt(); // ignored
1127
1128 // Read number of mappings
1129 int mappings = s.readInt();
1130 if (mappings < 0)
1131 throw new InvalidObjectException("Illegal mappings count: " +
1132 mappings);
1133
1134 int initialCapacity = (int) Math.min(
1135 // capacity chosen by number of mappings
1136 // and desired load (if >= 0.25)
1137 mappings * Math.min(1 / loadFactor, 4.0f),
1138 // we have limits...
1139 HashMap.MAXIMUM_CAPACITY);
1140 int capacity = 1;
1141 // find smallest power of two which holds all mappings
1142 while (capacity < initialCapacity) {
1143 capacity <<= 1;
1144 }
1145
1146 table = new Entry[capacity];
1147 threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
1148 useAltHashing = sun.misc.VM.isBooted() &&
1149 (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
1150
1151 init(); // Give subclass a chance to do its thing.
1152
1153 // Read the keys and values, and put the mappings in the HashMap
1154 for (int i=0; i<mappings; i++) {
1155 K key = (K) s.readObject();
1156 V value = (V) s.readObject();
1157 putForCreate(key, value);
1158 }
1159 }
1160
1161 // These methods are used when serializing HashSets
1162 int capacity() { return table.length; }
1163 float loadFactor() { return loadFactor; }
1164 }
|