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() {
285 return size;
286 }
287
288 /**
289 * Returns <tt>true</tt> if this map contains no key-value mappings.
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 private static final sun.misc.Unsafe UNSAFE;
201
202 /**
203 * Offset of "final" hashmask field we must set in
204 * readObject() method.
205 */
206 private static final long HASHMASK_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 HASHMASK_OFFSET = UNSAFE.objectFieldOffset(
239 HashMap.class.getDeclaredField("hashMask"));
240 } catch (NoSuchFieldException | SecurityException e) {
241 throw new Error("Failed to record hashMask 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 random mask value that is used for hashcode values associated with this
254 * instance to make hash collisions harder to find.
255 */
256 transient final int hashMask = sun.misc.Hashing.makeHashMask(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 h = hashMask;
347 if (k instanceof String) {
348 h ^= sun.misc.Hashing.stringHash32((String) k);
349 return h;
350 }
351 }
352
353 h ^= k.hashCode();
354
355 // This function ensures that hashCodes that differ only by
356 // constant multiples at each bit position have a bounded
357 // number of collisions (approximately 8 at default load factor).
358 h ^= (h >>> 20) ^ (h >>> 12);
359 h ^= (h >>> 7) ^ (h >>> 4);
360
361 return h;
362 }
363
364 /**
365 * Returns index for hash code h.
366 */
367 static int indexFor(int h, int length) {
368 return h & (length-1);
369 }
370
371 /**
372 * Returns the number of key-value mappings in this map.
373 *
374 * @return the number of key-value mappings in this map
375 */
376 public int size() {
377 return size;
378 }
379
380 /**
381 * Returns <tt>true</tt> if this map contains no key-value mappings.
389 /**
390 * Returns the value to which the specified key is mapped,
391 * or {@code null} if this map contains no mapping for the key.
392 *
393 * <p>More formally, if this map contains a mapping from a key
394 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
395 * key.equals(k))}, then this method returns {@code v}; otherwise
396 * it returns {@code null}. (There can be at most one such mapping.)
397 *
398 * <p>A return value of {@code null} does not <i>necessarily</i>
399 * indicate that the map contains no mapping for the key; it's also
400 * possible that the map explicitly maps the key to {@code null}.
401 * The {@link #containsKey containsKey} operation may be used to
402 * distinguish these two cases.
403 *
404 * @see #put(Object, Object)
405 */
406 public V get(Object key) {
407 if (key == null)
408 return getForNullKey();
409 Entry<K,V> entry = getEntry(key);
410
411 return null == entry ? null : entry.getValue();
412 }
413
414 /**
415 * Offloaded version of get() to look up null keys. Null keys map
416 * to index 0. This null case is split out into separate methods
417 * for the sake of performance in the two most commonly used
418 * operations (get and put), but incorporated with conditionals in
419 * others.
420 */
421 private V getForNullKey() {
422 for (Entry<K,V> e = table[0]; e != null; e = e.next) {
423 if (e.key == null)
424 return e.value;
425 }
426 return null;
427 }
428
429 /**
430 * Returns <tt>true</tt> if this map contains a mapping for the
431 * specified key.
432 *
433 * @param key The key whose presence in this map is to be tested
434 * @return <tt>true</tt> if this map contains a mapping for the specified
435 * key.
436 */
437 public boolean containsKey(Object key) {
438 return getEntry(key) != null;
439 }
440
441 /**
442 * Returns the entry associated with the specified key in the
443 * HashMap. Returns null if the HashMap contains no mapping
444 * for the key.
445 */
446 final Entry<K,V> getEntry(Object key) {
447 int hash = (key == null) ? 0 : hash(key);
448 for (Entry<K,V> e = table[indexFor(hash, table.length)];
449 e != null;
450 e = e.next) {
451 Object k;
452 if (e.hash == hash &&
453 ((k = e.key) == key || (key != null && key.equals(k))))
454 return e;
455 }
456 return null;
457 }
458
459
460 /**
461 * Associates the specified value with the specified key in this map.
462 * If the map previously contained a mapping for the key, the old
463 * value is replaced.
464 *
465 * @param key key with which the specified value is to be associated
466 * @param value value to be associated with the specified key
467 * @return the previous value associated with <tt>key</tt>, or
468 * <tt>null</tt> if there was no mapping for <tt>key</tt>.
469 * (A <tt>null</tt> return can also indicate that the map
470 * previously associated <tt>null</tt> with <tt>key</tt>.)
471 */
472 public V put(K key, V value) {
473 if (key == null)
474 return putForNullKey(value);
475 int hash = hash(key);
476 int i = indexFor(hash, table.length);
477 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
478 Object k;
479 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
480 V oldValue = e.value;
481 e.value = value;
482 e.recordAccess(this);
483 return oldValue;
484 }
485 }
486
487 modCount++;
488 addEntry(hash, key, value, i);
489 return null;
490 }
491
492 /**
493 * Offloaded version of put for null keys
494 */
495 private V putForNullKey(V value) {
496 for (Entry<K,V> e = table[0]; e != null; e = e.next) {
497 if (e.key == null) {
498 V oldValue = e.value;
499 e.value = value;
500 e.recordAccess(this);
501 return oldValue;
502 }
503 }
504 modCount++;
505 addEntry(0, null, value, 0);
506 return null;
507 }
508
509 /**
510 * This method is used instead of put by constructors and
511 * pseudoconstructors (clone, readObject). It does not resize the table,
512 * check for comodification, etc. It calls createEntry rather than
513 * addEntry.
514 */
515 private void putForCreate(K key, V value) {
516 int hash = null == key ? 0 : hash(key);
517 int i = indexFor(hash, table.length);
518
519 /**
520 * Look for preexisting entry for key. This will never happen for
521 * clone or deserialize. It will only happen for construction if the
522 * input Map is a sorted map whose ordering is inconsistent w/ equals.
523 */
524 for (Entry<K,V> e = table[i]; e != null; e = e.next) {
525 Object k;
526 if (e.hash == hash &&
527 ((k = e.key) == key || (key != null && key.equals(k)))) {
528 e.value = value;
529 return;
530 }
531 }
532
533 createEntry(hash, key, value, i);
534 }
535
536 private void putAllForCreate(Map<? extends K, ? extends V> m) {
544 * number of keys in this map reaches its threshold.
545 *
546 * If current capacity is MAXIMUM_CAPACITY, this method does not
547 * resize the map, but sets threshold to Integer.MAX_VALUE.
548 * This has the effect of preventing future calls.
549 *
550 * @param newCapacity the new capacity, MUST be a power of two;
551 * must be greater than current capacity unless current
552 * capacity is MAXIMUM_CAPACITY (in which case value
553 * is irrelevant).
554 */
555 void resize(int newCapacity) {
556 Entry[] oldTable = table;
557 int oldCapacity = oldTable.length;
558 if (oldCapacity == MAXIMUM_CAPACITY) {
559 threshold = Integer.MAX_VALUE;
560 return;
561 }
562
563 Entry[] newTable = new Entry[newCapacity];
564 boolean oldAltHashing = useAltHashing;
565 useAltHashing |= sun.misc.VM.isBooted() &&
566 (newCapacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
567 boolean rehash = oldAltHashing ^ useAltHashing;
568 transfer(newTable, rehash);
569 table = newTable;
570 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
571 }
572
573 /**
574 * Transfers all entries from current table to newTable.
575 */
576 void transfer(Entry[] newTable, boolean rehash) {
577 int newCapacity = newTable.length;
578 for (Entry<K,V> e : table) {
579 while(null != e) {
580 Entry<K,V> next = e.next;
581 if(rehash) {
582 e.hash = null == e.key ? 0 : hash(e.key);
583 }
584 int i = indexFor(e.hash, newCapacity);
585 e.next = newTable[i];
586 newTable[i] = e;
587 e = next;
588 }
589 }
590 }
591
592 /**
593 * Copies all of the mappings from the specified map to this map.
594 * These mappings will replace any mappings that this map had for
595 * any of the keys currently in the specified map.
596 *
597 * @param m mappings to be stored in this map
598 * @throws NullPointerException if the specified map is null
599 */
600 public void putAll(Map<? extends K, ? extends V> m) {
601 int numKeysToBeAdded = m.size();
602 if (numKeysToBeAdded == 0)
603 return;
604
605 /*
606 * Expand the map if the map if the number of mappings to be added
607 * is greater than or equal to threshold. This is conservative; the
629 /**
630 * Removes the mapping for the specified key from this map if present.
631 *
632 * @param key key whose mapping is to be removed from the map
633 * @return the previous value associated with <tt>key</tt>, or
634 * <tt>null</tt> if there was no mapping for <tt>key</tt>.
635 * (A <tt>null</tt> return can also indicate that the map
636 * previously associated <tt>null</tt> with <tt>key</tt>.)
637 */
638 public V remove(Object key) {
639 Entry<K,V> e = removeEntryForKey(key);
640 return (e == null ? null : e.value);
641 }
642
643 /**
644 * Removes and returns the entry associated with the specified key
645 * in the HashMap. Returns null if the HashMap contains no mapping
646 * for this key.
647 */
648 final Entry<K,V> removeEntryForKey(Object key) {
649 int hash = (key == null) ? 0 : hash(key);
650 int i = indexFor(hash, table.length);
651 Entry<K,V> prev = table[i];
652 Entry<K,V> e = prev;
653
654 while (e != null) {
655 Entry<K,V> next = e.next;
656 Object k;
657 if (e.hash == hash &&
658 ((k = e.key) == key || (key != null && key.equals(k)))) {
659 modCount++;
660 size--;
661 if (prev == e)
662 table[i] = next;
663 else
664 prev.next = next;
665 e.recordRemoval(this);
666 return e;
667 }
668 prev = e;
669 e = next;
670 }
671
672 return e;
673 }
674
675 /**
676 * Special version of remove for EntrySet using {@code Map.Entry.equals()}
677 * for matching.
678 */
679 final Entry<K,V> removeMapping(Object o) {
680 if (!(o instanceof Map.Entry))
681 return null;
682
683 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
684 Object key = entry.getKey();
685 int hash = (key == null) ? 0 : hash(key.hashCode());
686 int i = indexFor(hash, table.length);
687 Entry<K,V> prev = table[i];
688 Entry<K,V> e = prev;
689
690 while (e != null) {
691 Entry<K,V> next = e.next;
692 if (e.hash == hash && e.equals(entry)) {
693 modCount++;
694 size--;
695 if (prev == e)
696 table[i] = next;
697 else
760 HashMap<K,V> result = null;
761 try {
762 result = (HashMap<K,V>)super.clone();
763 } catch (CloneNotSupportedException e) {
764 // assert false;
765 }
766 result.table = new Entry[table.length];
767 result.entrySet = null;
768 result.modCount = 0;
769 result.size = 0;
770 result.init();
771 result.putAllForCreate(this);
772
773 return result;
774 }
775
776 static class Entry<K,V> implements Map.Entry<K,V> {
777 final K key;
778 V value;
779 Entry<K,V> next;
780 int hash;
781
782 /**
783 * Creates new entry.
784 */
785 Entry(int h, K k, V v, Entry<K,V> n) {
786 value = v;
787 next = n;
788 key = k;
789 hash = h;
790 }
791
792 public final K getKey() {
793 return key;
794 }
795
796 public final V getValue() {
797 return value;
798 }
799
800 public final V setValue(V newValue) {
834 */
835 void recordAccess(HashMap<K,V> m) {
836 }
837
838 /**
839 * This method is invoked whenever the entry is
840 * removed from the table.
841 */
842 void recordRemoval(HashMap<K,V> m) {
843 }
844 }
845
846 /**
847 * Adds a new entry with the specified key, value and hash code to
848 * the specified bucket. It is the responsibility of this
849 * method to resize the table if appropriate.
850 *
851 * Subclass overrides this to alter the behavior of put method.
852 */
853 void addEntry(int hash, K key, V value, int bucketIndex) {
854 if ((size >= threshold) && (null != table[bucketIndex])) {
855 resize(2 * table.length);
856 hash = hash(key);
857 bucketIndex = indexFor(hash, table.length);
858 }
859
860 createEntry(hash, key, value, bucketIndex);
861 }
862
863 /**
864 * Like addEntry except that this version is used when creating entries
865 * as part of Map construction or "pseudo-construction" (cloning,
866 * deserialization). This version needn't worry about resizing the table.
867 *
868 * Subclass overrides this to alter the behavior of HashMap(Map),
869 * clone, and readObject.
870 */
871 void createEntry(int hash, K key, V value, int bucketIndex) {
872 Entry<K,V> e = table[bucketIndex];
873 table[bucketIndex] = new Entry<>(hash, key, value, e);
874 size++;
875 }
876
877 private abstract class HashIterator<E> implements Iterator<E> {
878 Entry<K,V> next; // next entry to return
879 int expectedModCount; // For fast-fail
880 int index; // current slot
902
903 if ((next = e.next) == null) {
904 Entry[] t = table;
905 while (index < t.length && (next = t[index++]) == null)
906 ;
907 }
908 current = e;
909 return e;
910 }
911
912 public void remove() {
913 if (current == null)
914 throw new IllegalStateException();
915 if (modCount != expectedModCount)
916 throw new ConcurrentModificationException();
917 Object k = current.key;
918 current = null;
919 HashMap.this.removeEntryForKey(k);
920 expectedModCount = modCount;
921 }
922 }
923
924 private final class ValueIterator extends HashIterator<V> {
925 public V next() {
926 return nextEntry().value;
927 }
928 }
929
930 private final class KeyIterator extends HashIterator<K> {
931 public K next() {
932 return nextEntry().getKey();
933 }
934 }
935
936 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
937 public Map.Entry<K,V> next() {
938 return nextEntry();
939 }
940 }
941
1081 * mappings), followed by the key (Object) and value (Object)
1082 * for each key-value mapping. The key-value mappings are
1083 * emitted in no particular order.
1084 */
1085 private void writeObject(java.io.ObjectOutputStream s)
1086 throws IOException
1087 {
1088 Iterator<Map.Entry<K,V>> i =
1089 (size > 0) ? entrySet0().iterator() : null;
1090
1091 // Write out the threshold, loadfactor, and any hidden stuff
1092 s.defaultWriteObject();
1093
1094 // Write out number of buckets
1095 s.writeInt(table.length);
1096
1097 // Write out size (number of Mappings)
1098 s.writeInt(size);
1099
1100 // Write out keys and values (alternating)
1101 if (size > 0) {
1102 for(Map.Entry<K,V> e : entrySet0()) {
1103 s.writeObject(e.getKey());
1104 s.writeObject(e.getValue());
1105 }
1106 }
1107 }
1108
1109 private static final long serialVersionUID = 362498820763181265L;
1110
1111 /**
1112 * Reconstitute the {@code HashMap} instance from a stream (i.e.,
1113 * deserialize it).
1114 */
1115 private void readObject(java.io.ObjectInputStream s)
1116 throws IOException, ClassNotFoundException
1117 {
1118 // Read in the threshold (ignored), loadfactor, and any hidden stuff
1119 s.defaultReadObject();
1120 if (loadFactor <= 0 || Float.isNaN(loadFactor))
1121 throw new InvalidObjectException("Illegal load factor: " +
1122 loadFactor);
1123
1124 // set hashMask (can only happen after VM boot)
1125 Holder.UNSAFE.putIntVolatile(this, Holder.HASHMASK_OFFSET,
1126 sun.misc.Hashing.makeHashMask(this));
1127
1128 // Read in number of buckets and allocate the bucket array;
1129 s.readInt(); // ignored
1130
1131 // Read number of mappings
1132 int mappings = s.readInt();
1133 if (mappings < 0)
1134 throw new InvalidObjectException("Illegal mappings count: " +
1135 mappings);
1136
1137 int initialCapacity = (int) Math.min(
1138 // capacity chosen by number of mappings
1139 // and desired load (if >= 0.25)
1140 mappings * Math.min(1 / loadFactor, 4.0f),
1141 // we have limits...
1142 HashMap.MAXIMUM_CAPACITY);
1143 int capacity = 1;
1144 // find smallest power of two which holds all mappings
1145 while (capacity < initialCapacity) {
1146 capacity <<= 1;
1147 }
1148
1149 table = new Entry[capacity];
1150 threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
1151 useAltHashing = sun.misc.VM.isBooted() &&
1152 (capacity >= Holder.ALTERNATE_HASHING_THRESHOLD);
1153
1154 init(); // Give subclass a chance to do its thing.
1155
1156 // Read the keys and values, and put the mappings in the HashMap
1157 for (int i=0; i<mappings; i++) {
1158 K key = (K) s.readObject();
1159 V value = (V) s.readObject();
1160 putForCreate(key, value);
1161 }
1162 }
1163
1164 // These methods are used when serializing HashSets
1165 int capacity() { return table.length; }
1166 float loadFactor() { return loadFactor; }
1167 }
|