1. /*
  2. * @(#)HashMap.java 1.63 04/02/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. import java.io.*;
  9. /**
  10. * Hash table based implementation of the <tt>Map</tt> interface. This
  11. * implementation provides all of the optional map operations, and permits
  12. * <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt>
  13. * class is roughly equivalent to <tt>Hashtable</tt>, except that it is
  14. * unsynchronized and permits nulls.) This class makes no guarantees as to
  15. * the order of the map; in particular, it does not guarantee that the order
  16. * will remain constant over time.
  17. *
  18. * <p>This implementation provides constant-time performance for the basic
  19. * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
  20. * disperses the elements properly among the buckets. Iteration over
  21. * collection views requires time proportional to the "capacity" of the
  22. * <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
  23. * of key-value mappings). Thus, it's very important not to set the initial
  24. * capacity too high (or the load factor too low) if iteration performance is
  25. * important.
  26. *
  27. * <p>An instance of <tt>HashMap</tt> has two parameters that affect its
  28. * performance: <i>initial capacity</i> and <i>load factor</i>. The
  29. * <i>capacity</i> is the number of buckets in the hash table, and the initial
  30. * capacity is simply the capacity at the time the hash table is created. The
  31. * <i>load factor</i> is a measure of how full the hash table is allowed to
  32. * get before its capacity is automatically increased. When the number of
  33. * entries in the hash table exceeds the product of the load factor and the
  34. * current capacity, the capacity is roughly doubled by calling the
  35. * <tt>rehash</tt> method.
  36. *
  37. * <p>As a general rule, the default load factor (.75) offers a good tradeoff
  38. * between time and space costs. Higher values decrease the space overhead
  39. * but increase the lookup cost (reflected in most of the operations of the
  40. * <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>). The
  41. * expected number of entries in the map and its load factor should be taken
  42. * into account when setting its initial capacity, so as to minimize the
  43. * number of <tt>rehash</tt> operations. If the initial capacity is greater
  44. * than the maximum number of entries divided by the load factor, no
  45. * <tt>rehash</tt> operations will ever occur.
  46. *
  47. * <p>If many mappings are to be stored in a <tt>HashMap</tt> instance,
  48. * creating it with a sufficiently large capacity will allow the mappings to
  49. * be stored more efficiently than letting it perform automatic rehashing as
  50. * needed to grow the table.
  51. *
  52. * <p><b>Note that this implementation is not synchronized.</b> If multiple
  53. * threads access this map concurrently, and at least one of the threads
  54. * modifies the map structurally, it <i>must</i> be synchronized externally.
  55. * (A structural modification is any operation that adds or deletes one or
  56. * more mappings; merely changing the value associated with a key that an
  57. * instance already contains is not a structural modification.) This is
  58. * typically accomplished by synchronizing on some object that naturally
  59. * encapsulates the map. If no such object exists, the map should be
  60. * "wrapped" using the <tt>Collections.synchronizedMap</tt> method. This is
  61. * best done at creation time, to prevent accidental unsynchronized access to
  62. * the map: <pre> Map m = Collections.synchronizedMap(new HashMap(...));
  63. * </pre>
  64. *
  65. * <p>The iterators returned by all of this class's "collection view methods"
  66. * are <i>fail-fast</i>: if the map is structurally modified at any time after
  67. * the iterator is created, in any way except through the iterator's own
  68. * <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
  69. * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
  70. * modification, the iterator fails quickly and cleanly, rather than risking
  71. * arbitrary, non-deterministic behavior at an undetermined time in the
  72. * future.
  73. *
  74. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  75. * as it is, generally speaking, impossible to make any hard guarantees in the
  76. * presence of unsynchronized concurrent modification. Fail-fast iterators
  77. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  78. * Therefore, it would be wrong to write a program that depended on this
  79. * exception for its correctness: <i>the fail-fast behavior of iterators
  80. * should be used only to detect bugs.</i>
  81. *
  82. * <p>This class is a member of the
  83. * <a href="{@docRoot}/../guide/collections/index.html">
  84. * Java Collections Framework</a>.
  85. *
  86. * @author Doug Lea
  87. * @author Josh Bloch
  88. * @author Arthur van Hoff
  89. * @author Neal Gafter
  90. * @version 1.63, 02/19/04
  91. * @see Object#hashCode()
  92. * @see Collection
  93. * @see Map
  94. * @see TreeMap
  95. * @see Hashtable
  96. * @since 1.2
  97. */
  98. public class HashMap<K,V>
  99. extends AbstractMap<K,V>
  100. implements Map<K,V>, Cloneable, Serializable
  101. {
  102. /**
  103. * The default initial capacity - MUST be a power of two.
  104. */
  105. static final int DEFAULT_INITIAL_CAPACITY = 16;
  106. /**
  107. * The maximum capacity, used if a higher value is implicitly specified
  108. * by either of the constructors with arguments.
  109. * MUST be a power of two <= 1<<30.
  110. */
  111. static final int MAXIMUM_CAPACITY = 1 << 30;
  112. /**
  113. * The load factor used when none specified in constructor.
  114. **/
  115. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  116. /**
  117. * The table, resized as necessary. Length MUST Always be a power of two.
  118. */
  119. transient Entry[] table;
  120. /**
  121. * The number of key-value mappings contained in this identity hash map.
  122. */
  123. transient int size;
  124. /**
  125. * The next size value at which to resize (capacity * load factor).
  126. * @serial
  127. */
  128. int threshold;
  129. /**
  130. * The load factor for the hash table.
  131. *
  132. * @serial
  133. */
  134. final float loadFactor;
  135. /**
  136. * The number of times this HashMap has been structurally modified
  137. * Structural modifications are those that change the number of mappings in
  138. * the HashMap or otherwise modify its internal structure (e.g.,
  139. * rehash). This field is used to make iterators on Collection-views of
  140. * the HashMap fail-fast. (See ConcurrentModificationException).
  141. */
  142. transient volatile int modCount;
  143. /**
  144. * Constructs an empty <tt>HashMap</tt> with the specified initial
  145. * capacity and load factor.
  146. *
  147. * @param initialCapacity The initial capacity.
  148. * @param loadFactor The load factor.
  149. * @throws IllegalArgumentException if the initial capacity is negative
  150. * or the load factor is nonpositive.
  151. */
  152. public HashMap(int initialCapacity, float loadFactor) {
  153. if (initialCapacity < 0)
  154. throw new IllegalArgumentException("Illegal initial capacity: " +
  155. initialCapacity);
  156. if (initialCapacity > MAXIMUM_CAPACITY)
  157. initialCapacity = MAXIMUM_CAPACITY;
  158. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  159. throw new IllegalArgumentException("Illegal load factor: " +
  160. loadFactor);
  161. // Find a power of 2 >= initialCapacity
  162. int capacity = 1;
  163. while (capacity < initialCapacity)
  164. capacity <<= 1;
  165. this.loadFactor = loadFactor;
  166. threshold = (int)(capacity * loadFactor);
  167. table = new Entry[capacity];
  168. init();
  169. }
  170. /**
  171. * Constructs an empty <tt>HashMap</tt> with the specified initial
  172. * capacity and the default load factor (0.75).
  173. *
  174. * @param initialCapacity the initial capacity.
  175. * @throws IllegalArgumentException if the initial capacity is negative.
  176. */
  177. public HashMap(int initialCapacity) {
  178. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  179. }
  180. /**
  181. * Constructs an empty <tt>HashMap</tt> with the default initial capacity
  182. * (16) and the default load factor (0.75).
  183. */
  184. public HashMap() {
  185. this.loadFactor = DEFAULT_LOAD_FACTOR;
  186. threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
  187. table = new Entry[DEFAULT_INITIAL_CAPACITY];
  188. init();
  189. }
  190. /**
  191. * Constructs a new <tt>HashMap</tt> with the same mappings as the
  192. * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
  193. * default load factor (0.75) and an initial capacity sufficient to
  194. * hold the mappings in the specified <tt>Map</tt>.
  195. *
  196. * @param m the map whose mappings are to be placed in this map.
  197. * @throws NullPointerException if the specified map is null.
  198. */
  199. public HashMap(Map<? extends K, ? extends V> m) {
  200. this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
  201. DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
  202. putAllForCreate(m);
  203. }
  204. // internal utilities
  205. /**
  206. * Initialization hook for subclasses. This method is called
  207. * in all constructors and pseudo-constructors (clone, readObject)
  208. * after HashMap has been initialized but before any entries have
  209. * been inserted. (In the absence of this method, readObject would
  210. * require explicit knowledge of subclasses.)
  211. */
  212. void init() {
  213. }
  214. /**
  215. * Value representing null keys inside tables.
  216. */
  217. static final Object NULL_KEY = new Object();
  218. /**
  219. * Returns internal representation for key. Use NULL_KEY if key is null.
  220. */
  221. static <T> T maskNull(T key) {
  222. return key == null ? (T)NULL_KEY : key;
  223. }
  224. /**
  225. * Returns key represented by specified internal representation.
  226. */
  227. static <T> T unmaskNull(T key) {
  228. return (key == NULL_KEY ? null : key);
  229. }
  230. /**
  231. * Returns a hash value for the specified object. In addition to
  232. * the object's own hashCode, this method applies a "supplemental
  233. * hash function," which defends against poor quality hash functions.
  234. * This is critical because HashMap uses power-of two length
  235. * hash tables.<p>
  236. *
  237. * The shift distances in this function were chosen as the result
  238. * of an automated search over the entire four-dimensional search space.
  239. */
  240. static int hash(Object x) {
  241. int h = x.hashCode();
  242. h += ~(h << 9);
  243. h ^= (h >>> 14);
  244. h += (h << 4);
  245. h ^= (h >>> 10);
  246. return h;
  247. }
  248. /**
  249. * Check for equality of non-null reference x and possibly-null y.
  250. */
  251. static boolean eq(Object x, Object y) {
  252. return x == y || x.equals(y);
  253. }
  254. /**
  255. * Returns index for hash code h.
  256. */
  257. static int indexFor(int h, int length) {
  258. return h & (length-1);
  259. }
  260. /**
  261. * Returns the number of key-value mappings in this map.
  262. *
  263. * @return the number of key-value mappings in this map.
  264. */
  265. public int size() {
  266. return size;
  267. }
  268. /**
  269. * Returns <tt>true</tt> if this map contains no key-value mappings.
  270. *
  271. * @return <tt>true</tt> if this map contains no key-value mappings.
  272. */
  273. public boolean isEmpty() {
  274. return size == 0;
  275. }
  276. /**
  277. * Returns the value to which the specified key is mapped in this identity
  278. * hash map, or <tt>null</tt> if the map contains no mapping for this key.
  279. * A return value of <tt>null</tt> does not <i>necessarily</i> indicate
  280. * that the map contains no mapping for the key; it is also possible that
  281. * the map explicitly maps the key to <tt>null</tt>. The
  282. * <tt>containsKey</tt> method may be used to distinguish these two cases.
  283. *
  284. * @param key the key whose associated value is to be returned.
  285. * @return the value to which this map maps the specified key, or
  286. * <tt>null</tt> if the map contains no mapping for this key.
  287. * @see #put(Object, Object)
  288. */
  289. public V get(Object key) {
  290. Object k = maskNull(key);
  291. int hash = hash(k);
  292. int i = indexFor(hash, table.length);
  293. Entry<K,V> e = table[i];
  294. while (true) {
  295. if (e == null)
  296. return null;
  297. if (e.hash == hash && eq(k, e.key))
  298. return e.value;
  299. e = e.next;
  300. }
  301. }
  302. /**
  303. * Returns <tt>true</tt> if this map contains a mapping for the
  304. * specified key.
  305. *
  306. * @param key The key whose presence in this map is to be tested
  307. * @return <tt>true</tt> if this map contains a mapping for the specified
  308. * key.
  309. */
  310. public boolean containsKey(Object key) {
  311. Object k = maskNull(key);
  312. int hash = hash(k);
  313. int i = indexFor(hash, table.length);
  314. Entry e = table[i];
  315. while (e != null) {
  316. if (e.hash == hash && eq(k, e.key))
  317. return true;
  318. e = e.next;
  319. }
  320. return false;
  321. }
  322. /**
  323. * Returns the entry associated with the specified key in the
  324. * HashMap. Returns null if the HashMap contains no mapping
  325. * for this key.
  326. */
  327. Entry<K,V> getEntry(Object key) {
  328. Object k = maskNull(key);
  329. int hash = hash(k);
  330. int i = indexFor(hash, table.length);
  331. Entry<K,V> e = table[i];
  332. while (e != null && !(e.hash == hash && eq(k, e.key)))
  333. e = e.next;
  334. return e;
  335. }
  336. /**
  337. * Associates the specified value with the specified key in this map.
  338. * If the map previously contained a mapping for this key, the old
  339. * value is replaced.
  340. *
  341. * @param key key with which the specified value is to be associated.
  342. * @param value value to be associated with the specified key.
  343. * @return previous value associated with specified key, or <tt>null</tt>
  344. * if there was no mapping for key. A <tt>null</tt> return can
  345. * also indicate that the HashMap previously associated
  346. * <tt>null</tt> with the specified key.
  347. */
  348. public V put(K key, V value) {
  349. K k = maskNull(key);
  350. int hash = hash(k);
  351. int i = indexFor(hash, table.length);
  352. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  353. if (e.hash == hash && eq(k, e.key)) {
  354. V oldValue = e.value;
  355. e.value = value;
  356. e.recordAccess(this);
  357. return oldValue;
  358. }
  359. }
  360. modCount++;
  361. addEntry(hash, k, value, i);
  362. return null;
  363. }
  364. /**
  365. * This method is used instead of put by constructors and
  366. * pseudoconstructors (clone, readObject). It does not resize the table,
  367. * check for comodification, etc. It calls createEntry rather than
  368. * addEntry.
  369. */
  370. private void putForCreate(K key, V value) {
  371. K k = maskNull(key);
  372. int hash = hash(k);
  373. int i = indexFor(hash, table.length);
  374. /**
  375. * Look for preexisting entry for key. This will never happen for
  376. * clone or deserialize. It will only happen for construction if the
  377. * input Map is a sorted map whose ordering is inconsistent w/ equals.
  378. */
  379. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  380. if (e.hash == hash && eq(k, e.key)) {
  381. e.value = value;
  382. return;
  383. }
  384. }
  385. createEntry(hash, k, value, i);
  386. }
  387. void putAllForCreate(Map<? extends K, ? extends V> m) {
  388. for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
  389. Map.Entry<? extends K, ? extends V> e = i.next();
  390. putForCreate(e.getKey(), e.getValue());
  391. }
  392. }
  393. /**
  394. * Rehashes the contents of this map into a new array with a
  395. * larger capacity. This method is called automatically when the
  396. * number of keys in this map reaches its threshold.
  397. *
  398. * If current capacity is MAXIMUM_CAPACITY, this method does not
  399. * resize the map, but sets threshold to Integer.MAX_VALUE.
  400. * This has the effect of preventing future calls.
  401. *
  402. * @param newCapacity the new capacity, MUST be a power of two;
  403. * must be greater than current capacity unless current
  404. * capacity is MAXIMUM_CAPACITY (in which case value
  405. * is irrelevant).
  406. */
  407. void resize(int newCapacity) {
  408. Entry[] oldTable = table;
  409. int oldCapacity = oldTable.length;
  410. if (oldCapacity == MAXIMUM_CAPACITY) {
  411. threshold = Integer.MAX_VALUE;
  412. return;
  413. }
  414. Entry[] newTable = new Entry[newCapacity];
  415. transfer(newTable);
  416. table = newTable;
  417. threshold = (int)(newCapacity * loadFactor);
  418. }
  419. /**
  420. * Transfer all entries from current table to newTable.
  421. */
  422. void transfer(Entry[] newTable) {
  423. Entry[] src = table;
  424. int newCapacity = newTable.length;
  425. for (int j = 0; j < src.length; j++) {
  426. Entry<K,V> e = src[j];
  427. if (e != null) {
  428. src[j] = null;
  429. do {
  430. Entry<K,V> next = e.next;
  431. int i = indexFor(e.hash, newCapacity);
  432. e.next = newTable[i];
  433. newTable[i] = e;
  434. e = next;
  435. } while (e != null);
  436. }
  437. }
  438. }
  439. /**
  440. * Copies all of the mappings from the specified map to this map
  441. * These mappings will replace any mappings that
  442. * this map had for any of the keys currently in the specified map.
  443. *
  444. * @param m mappings to be stored in this map.
  445. * @throws NullPointerException if the specified map is null.
  446. */
  447. public void putAll(Map<? extends K, ? extends V> m) {
  448. int numKeysToBeAdded = m.size();
  449. if (numKeysToBeAdded == 0)
  450. return;
  451. /*
  452. * Expand the map if the map if the number of mappings to be added
  453. * is greater than or equal to threshold. This is conservative; the
  454. * obvious condition is (m.size() + size) >= threshold, but this
  455. * condition could result in a map with twice the appropriate capacity,
  456. * if the keys to be added overlap with the keys already in this map.
  457. * By using the conservative calculation, we subject ourself
  458. * to at most one extra resize.
  459. */
  460. if (numKeysToBeAdded > threshold) {
  461. int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
  462. if (targetCapacity > MAXIMUM_CAPACITY)
  463. targetCapacity = MAXIMUM_CAPACITY;
  464. int newCapacity = table.length;
  465. while (newCapacity < targetCapacity)
  466. newCapacity <<= 1;
  467. if (newCapacity > table.length)
  468. resize(newCapacity);
  469. }
  470. for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
  471. Map.Entry<? extends K, ? extends V> e = i.next();
  472. put(e.getKey(), e.getValue());
  473. }
  474. }
  475. /**
  476. * Removes the mapping for this key from this map if present.
  477. *
  478. * @param key key whose mapping is to be removed from the map.
  479. * @return previous value associated with specified key, or <tt>null</tt>
  480. * if there was no mapping for key. A <tt>null</tt> return can
  481. * also indicate that the map previously associated <tt>null</tt>
  482. * with the specified key.
  483. */
  484. public V remove(Object key) {
  485. Entry<K,V> e = removeEntryForKey(key);
  486. return (e == null ? null : e.value);
  487. }
  488. /**
  489. * Removes and returns the entry associated with the specified key
  490. * in the HashMap. Returns null if the HashMap contains no mapping
  491. * for this key.
  492. */
  493. Entry<K,V> removeEntryForKey(Object key) {
  494. Object k = maskNull(key);
  495. int hash = hash(k);
  496. int i = indexFor(hash, table.length);
  497. Entry<K,V> prev = table[i];
  498. Entry<K,V> e = prev;
  499. while (e != null) {
  500. Entry<K,V> next = e.next;
  501. if (e.hash == hash && eq(k, e.key)) {
  502. modCount++;
  503. size--;
  504. if (prev == e)
  505. table[i] = next;
  506. else
  507. prev.next = next;
  508. e.recordRemoval(this);
  509. return e;
  510. }
  511. prev = e;
  512. e = next;
  513. }
  514. return e;
  515. }
  516. /**
  517. * Special version of remove for EntrySet.
  518. */
  519. Entry<K,V> removeMapping(Object o) {
  520. if (!(o instanceof Map.Entry))
  521. return null;
  522. Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
  523. Object k = maskNull(entry.getKey());
  524. int hash = hash(k);
  525. int i = indexFor(hash, table.length);
  526. Entry<K,V> prev = table[i];
  527. Entry<K,V> e = prev;
  528. while (e != null) {
  529. Entry<K,V> next = e.next;
  530. if (e.hash == hash && e.equals(entry)) {
  531. modCount++;
  532. size--;
  533. if (prev == e)
  534. table[i] = next;
  535. else
  536. prev.next = next;
  537. e.recordRemoval(this);
  538. return e;
  539. }
  540. prev = e;
  541. e = next;
  542. }
  543. return e;
  544. }
  545. /**
  546. * Removes all mappings from this map.
  547. */
  548. public void clear() {
  549. modCount++;
  550. Entry[] tab = table;
  551. for (int i = 0; i < tab.length; i++)
  552. tab[i] = null;
  553. size = 0;
  554. }
  555. /**
  556. * Returns <tt>true</tt> if this map maps one or more keys to the
  557. * specified value.
  558. *
  559. * @param value value whose presence in this map is to be tested.
  560. * @return <tt>true</tt> if this map maps one or more keys to the
  561. * specified value.
  562. */
  563. public boolean containsValue(Object value) {
  564. if (value == null)
  565. return containsNullValue();
  566. Entry[] tab = table;
  567. for (int i = 0; i < tab.length ; i++)
  568. for (Entry e = tab[i] ; e != null ; e = e.next)
  569. if (value.equals(e.value))
  570. return true;
  571. return false;
  572. }
  573. /**
  574. * Special-case code for containsValue with null argument
  575. **/
  576. private boolean containsNullValue() {
  577. Entry[] tab = table;
  578. for (int i = 0; i < tab.length ; i++)
  579. for (Entry e = tab[i] ; e != null ; e = e.next)
  580. if (e.value == null)
  581. return true;
  582. return false;
  583. }
  584. /**
  585. * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
  586. * values themselves are not cloned.
  587. *
  588. * @return a shallow copy of this map.
  589. */
  590. public Object clone() {
  591. HashMap<K,V> result = null;
  592. try {
  593. result = (HashMap<K,V>)super.clone();
  594. } catch (CloneNotSupportedException e) {
  595. // assert false;
  596. }
  597. result.table = new Entry[table.length];
  598. result.entrySet = null;
  599. result.modCount = 0;
  600. result.size = 0;
  601. result.init();
  602. result.putAllForCreate(this);
  603. return result;
  604. }
  605. static class Entry<K,V> implements Map.Entry<K,V> {
  606. final K key;
  607. V value;
  608. final int hash;
  609. Entry<K,V> next;
  610. /**
  611. * Create new entry.
  612. */
  613. Entry(int h, K k, V v, Entry<K,V> n) {
  614. value = v;
  615. next = n;
  616. key = k;
  617. hash = h;
  618. }
  619. public K getKey() {
  620. return HashMap.<K>unmaskNull(key);
  621. }
  622. public V getValue() {
  623. return value;
  624. }
  625. public V setValue(V newValue) {
  626. V oldValue = value;
  627. value = newValue;
  628. return oldValue;
  629. }
  630. public boolean equals(Object o) {
  631. if (!(o instanceof Map.Entry))
  632. return false;
  633. Map.Entry e = (Map.Entry)o;
  634. Object k1 = getKey();
  635. Object k2 = e.getKey();
  636. if (k1 == k2 || (k1 != null && k1.equals(k2))) {
  637. Object v1 = getValue();
  638. Object v2 = e.getValue();
  639. if (v1 == v2 || (v1 != null && v1.equals(v2)))
  640. return true;
  641. }
  642. return false;
  643. }
  644. public int hashCode() {
  645. return (key==NULL_KEY ? 0 : key.hashCode()) ^
  646. (value==null ? 0 : value.hashCode());
  647. }
  648. public String toString() {
  649. return getKey() + "=" + getValue();
  650. }
  651. /**
  652. * This method is invoked whenever the value in an entry is
  653. * overwritten by an invocation of put(k,v) for a key k that's already
  654. * in the HashMap.
  655. */
  656. void recordAccess(HashMap<K,V> m) {
  657. }
  658. /**
  659. * This method is invoked whenever the entry is
  660. * removed from the table.
  661. */
  662. void recordRemoval(HashMap<K,V> m) {
  663. }
  664. }
  665. /**
  666. * Add a new entry with the specified key, value and hash code to
  667. * the specified bucket. It is the responsibility of this
  668. * method to resize the table if appropriate.
  669. *
  670. * Subclass overrides this to alter the behavior of put method.
  671. */
  672. void addEntry(int hash, K key, V value, int bucketIndex) {
  673. Entry<K,V> e = table[bucketIndex];
  674. table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
  675. if (size++ >= threshold)
  676. resize(2 * table.length);
  677. }
  678. /**
  679. * Like addEntry except that this version is used when creating entries
  680. * as part of Map construction or "pseudo-construction" (cloning,
  681. * deserialization). This version needn't worry about resizing the table.
  682. *
  683. * Subclass overrides this to alter the behavior of HashMap(Map),
  684. * clone, and readObject.
  685. */
  686. void createEntry(int hash, K key, V value, int bucketIndex) {
  687. Entry<K,V> e = table[bucketIndex];
  688. table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
  689. size++;
  690. }
  691. private abstract class HashIterator<E> implements Iterator<E> {
  692. Entry<K,V> next; // next entry to return
  693. int expectedModCount; // For fast-fail
  694. int index; // current slot
  695. Entry<K,V> current; // current entry
  696. HashIterator() {
  697. expectedModCount = modCount;
  698. Entry[] t = table;
  699. int i = t.length;
  700. Entry<K,V> n = null;
  701. if (size != 0) { // advance to first entry
  702. while (i > 0 && (n = t[--i]) == null)
  703. ;
  704. }
  705. next = n;
  706. index = i;
  707. }
  708. public boolean hasNext() {
  709. return next != null;
  710. }
  711. Entry<K,V> nextEntry() {
  712. if (modCount != expectedModCount)
  713. throw new ConcurrentModificationException();
  714. Entry<K,V> e = next;
  715. if (e == null)
  716. throw new NoSuchElementException();
  717. Entry<K,V> n = e.next;
  718. Entry[] t = table;
  719. int i = index;
  720. while (n == null && i > 0)
  721. n = t[--i];
  722. index = i;
  723. next = n;
  724. return current = e;
  725. }
  726. public void remove() {
  727. if (current == null)
  728. throw new IllegalStateException();
  729. if (modCount != expectedModCount)
  730. throw new ConcurrentModificationException();
  731. Object k = current.key;
  732. current = null;
  733. HashMap.this.removeEntryForKey(k);
  734. expectedModCount = modCount;
  735. }
  736. }
  737. private class ValueIterator extends HashIterator<V> {
  738. public V next() {
  739. return nextEntry().value;
  740. }
  741. }
  742. private class KeyIterator extends HashIterator<K> {
  743. public K next() {
  744. return nextEntry().getKey();
  745. }
  746. }
  747. private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
  748. public Map.Entry<K,V> next() {
  749. return nextEntry();
  750. }
  751. }
  752. // Subclass overrides these to alter behavior of views' iterator() method
  753. Iterator<K> newKeyIterator() {
  754. return new KeyIterator();
  755. }
  756. Iterator<V> newValueIterator() {
  757. return new ValueIterator();
  758. }
  759. Iterator<Map.Entry<K,V>> newEntryIterator() {
  760. return new EntryIterator();
  761. }
  762. // Views
  763. private transient Set<Map.Entry<K,V>> entrySet = null;
  764. /**
  765. * Returns a set view of the keys contained in this map. The set is
  766. * backed by the map, so changes to the map are reflected in the set, and
  767. * vice-versa. The set supports element removal, which removes the
  768. * corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
  769. * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
  770. * <tt>clear</tt> operations. It does not support the <tt>add</tt> or
  771. * <tt>addAll</tt> operations.
  772. *
  773. * @return a set view of the keys contained in this map.
  774. */
  775. public Set<K> keySet() {
  776. Set<K> ks = keySet;
  777. return (ks != null ? ks : (keySet = new KeySet()));
  778. }
  779. private class KeySet extends AbstractSet<K> {
  780. public Iterator<K> iterator() {
  781. return newKeyIterator();
  782. }
  783. public int size() {
  784. return size;
  785. }
  786. public boolean contains(Object o) {
  787. return containsKey(o);
  788. }
  789. public boolean remove(Object o) {
  790. return HashMap.this.removeEntryForKey(o) != null;
  791. }
  792. public void clear() {
  793. HashMap.this.clear();
  794. }
  795. }
  796. /**
  797. * Returns a collection view of the values contained in this map. The
  798. * collection is backed by the map, so changes to the map are reflected in
  799. * the collection, and vice-versa. The collection supports element
  800. * removal, which removes the corresponding mapping from this map, via the
  801. * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  802. * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
  803. * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
  804. *
  805. * @return a collection view of the values contained in this map.
  806. */
  807. public Collection<V> values() {
  808. Collection<V> vs = values;
  809. return (vs != null ? vs : (values = new Values()));
  810. }
  811. private class Values extends AbstractCollection<V> {
  812. public Iterator<V> iterator() {
  813. return newValueIterator();
  814. }
  815. public int size() {
  816. return size;
  817. }
  818. public boolean contains(Object o) {
  819. return containsValue(o);
  820. }
  821. public void clear() {
  822. HashMap.this.clear();
  823. }
  824. }
  825. /**
  826. * Returns a collection view of the mappings contained in this map. Each
  827. * element in the returned collection is a <tt>Map.Entry</tt>. The
  828. * collection is backed by the map, so changes to the map are reflected in
  829. * the collection, and vice-versa. The collection supports element
  830. * removal, which removes the corresponding mapping from the map, via the
  831. * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  832. * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
  833. * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
  834. *
  835. * @return a collection view of the mappings contained in this map.
  836. * @see Map.Entry
  837. */
  838. public Set<Map.Entry<K,V>> entrySet() {
  839. Set<Map.Entry<K,V>> es = entrySet;
  840. return (es != null ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet()));
  841. }
  842. private class EntrySet extends AbstractSet/*<Map.Entry<K,V>>*/ {
  843. public Iterator/*<Map.Entry<K,V>>*/ iterator() {
  844. return newEntryIterator();
  845. }
  846. public boolean contains(Object o) {
  847. if (!(o instanceof Map.Entry))
  848. return false;
  849. Map.Entry<K,V> e = (Map.Entry<K,V>) o;
  850. Entry<K,V> candidate = getEntry(e.getKey());
  851. return candidate != null && candidate.equals(e);
  852. }
  853. public boolean remove(Object o) {
  854. return removeMapping(o) != null;
  855. }
  856. public int size() {
  857. return size;
  858. }
  859. public void clear() {
  860. HashMap.this.clear();
  861. }
  862. }
  863. /**
  864. * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
  865. * serialize it).
  866. *
  867. * @serialData The <i>capacity</i> of the HashMap (the length of the
  868. * bucket array) is emitted (int), followed by the
  869. * <i>size</i> of the HashMap (the number of key-value
  870. * mappings), followed by the key (Object) and value (Object)
  871. * for each key-value mapping represented by the HashMap
  872. * The key-value mappings are emitted in the order that they
  873. * are returned by <tt>entrySet().iterator()</tt>.
  874. *
  875. */
  876. private void writeObject(java.io.ObjectOutputStream s)
  877. throws IOException
  878. {
  879. // Write out the threshold, loadfactor, and any hidden stuff
  880. s.defaultWriteObject();
  881. // Write out number of buckets
  882. s.writeInt(table.length);
  883. // Write out size (number of Mappings)
  884. s.writeInt(size);
  885. // Write out keys and values (alternating)
  886. for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
  887. Map.Entry<K,V> e = i.next();
  888. s.writeObject(e.getKey());
  889. s.writeObject(e.getValue());
  890. }
  891. }
  892. private static final long serialVersionUID = 362498820763181265L;
  893. /**
  894. * Reconstitute the <tt>HashMap</tt> instance from a stream (i.e.,
  895. * deserialize it).
  896. */
  897. private void readObject(java.io.ObjectInputStream s)
  898. throws IOException, ClassNotFoundException
  899. {
  900. // Read in the threshold, loadfactor, and any hidden stuff
  901. s.defaultReadObject();
  902. // Read in number of buckets and allocate the bucket array;
  903. int numBuckets = s.readInt();
  904. table = new Entry[numBuckets];
  905. init(); // Give subclass a chance to do its thing.
  906. // Read in size (number of Mappings)
  907. int size = s.readInt();
  908. // Read the keys and values, and put the mappings in the HashMap
  909. for (int i=0; i<size; i++) {
  910. K key = (K) s.readObject();
  911. V value = (V) s.readObject();
  912. putForCreate(key, value);
  913. }
  914. }
  915. // These methods are used when serializing HashSets
  916. int capacity() { return table.length; }
  917. float loadFactor() { return loadFactor; }
  918. }