1. /*
  2. * @(#)WeakHashMap.java 1.30 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.lang.ref.WeakReference;
  9. import java.lang.ref.ReferenceQueue;
  10. /**
  11. * A hashtable-based <tt>Map</tt> implementation with <em>weak keys</em>.
  12. * An entry in a <tt>WeakHashMap</tt> will automatically be removed when
  13. * its key is no longer in ordinary use. More precisely, the presence of a
  14. * mapping for a given key will not prevent the key from being discarded by the
  15. * garbage collector, that is, made finalizable, finalized, and then reclaimed.
  16. * When a key has been discarded its entry is effectively removed from the map,
  17. * so this class behaves somewhat differently than other <tt>Map</tt>
  18. * implementations.
  19. *
  20. * <p> Both null values and the null key are supported. This class has
  21. * performance characteristics similar to those of the <tt>HashMap</tt>
  22. * class, and has the same efficiency parameters of <em>initial capacity</em>
  23. * and <em>load factor</em>.
  24. *
  25. * <p> Like most collection classes, this class is not synchronized. A
  26. * synchronized <tt>WeakHashMap</tt> may be constructed using the
  27. * <tt>Collections.synchronizedMap</tt> method.
  28. *
  29. * <p> This class is intended primarily for use with key objects whose
  30. * <tt>equals</tt> methods test for object identity using the
  31. * <tt>==</tt> operator. Once such a key is discarded it can never be
  32. * recreated, so it is impossible to do a lookup of that key in a
  33. * <tt>WeakHashMap</tt> at some later time and be surprised that its entry
  34. * has been removed. This class will work perfectly well with key objects
  35. * whose <tt>equals</tt> methods are not based upon object identity, such
  36. * as <tt>String</tt> instances. With such recreatable key objects,
  37. * however, the automatic removal of <tt>WeakHashMap</tt> entries whose
  38. * keys have been discarded may prove to be confusing.
  39. *
  40. * <p> The behavior of the <tt>WeakHashMap</tt> class depends in part upon
  41. * the actions of the garbage collector, so several familiar (though not
  42. * required) <tt>Map</tt> invariants do not hold for this class. Because
  43. * the garbage collector may discard keys at any time, a
  44. * <tt>WeakHashMap</tt> may behave as though an unknown thread is silently
  45. * removing entries. In particular, even if you synchronize on a
  46. * <tt>WeakHashMap</tt> instance and invoke none of its mutator methods, it
  47. * is possible for the <tt>size</tt> method to return smaller values over
  48. * time, for the <tt>isEmpty</tt> method to return <tt>false</tt> and
  49. * then <tt>true</tt>, for the <tt>containsKey</tt> method to return
  50. * <tt>true</tt> and later <tt>false</tt> for a given key, for the
  51. * <tt>get</tt> method to return a value for a given key but later return
  52. * <tt>null</tt>, for the <tt>put</tt> method to return
  53. * <tt>null</tt> and the <tt>remove</tt> method to return
  54. * <tt>false</tt> for a key that previously appeared to be in the map, and
  55. * for successive examinations of the key set, the value set, and the entry set
  56. * to yield successively smaller numbers of elements.
  57. *
  58. * <p> Each key object in a <tt>WeakHashMap</tt> is stored indirectly as
  59. * the referent of a weak reference. Therefore a key will automatically be
  60. * removed only after the weak references to it, both inside and outside of the
  61. * map, have been cleared by the garbage collector.
  62. *
  63. * <p> <strong>Implementation note:</strong> The value objects in a
  64. * <tt>WeakHashMap</tt> are held by ordinary strong references. Thus care
  65. * should be taken to ensure that value objects do not strongly refer to their
  66. * own keys, either directly or indirectly, since that will prevent the keys
  67. * from being discarded. Note that a value object may refer indirectly to its
  68. * key via the <tt>WeakHashMap</tt> itself; that is, a value object may
  69. * strongly refer to some other key object whose associated value object, in
  70. * turn, strongly refers to the key of the first value object. One way
  71. * to deal with this is to wrap values themselves within
  72. * <tt>WeakReferences</tt> before
  73. * inserting, as in: <tt>m.put(key, new WeakReference(value))</tt>,
  74. * and then unwrapping upon each <tt>get</tt>.
  75. *
  76. * <p>The iterators returned by all of this class's "collection view methods"
  77. * are <i>fail-fast</i>: if the map is structurally modified at any time after
  78. * the iterator is created, in any way except through the iterator's own
  79. * <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
  80. * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
  81. * modification, the iterator fails quickly and cleanly, rather than risking
  82. * arbitrary, non-deterministic behavior at an undetermined time in the
  83. * future.
  84. *
  85. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  86. * as it is, generally speaking, impossible to make any hard guarantees in the
  87. * presence of unsynchronized concurrent modification. Fail-fast iterators
  88. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  89. * Therefore, it would be wrong to write a program that depended on this
  90. * exception for its correctness: <i>the fail-fast behavior of iterators
  91. * should be used only to detect bugs.</i>
  92. *
  93. * <p>This class is a member of the
  94. * <a href="{@docRoot}/../guide/collections/index.html">
  95. * Java Collections Framework</a>.
  96. *
  97. * @version 1.30, 02/19/04
  98. * @author Doug Lea
  99. * @author Josh Bloch
  100. * @author Mark Reinhold
  101. * @since 1.2
  102. * @see java.util.HashMap
  103. * @see java.lang.ref.WeakReference
  104. */
  105. public class WeakHashMap<K,V>
  106. extends AbstractMap<K,V>
  107. implements Map<K,V> {
  108. /**
  109. * The default initial capacity -- MUST be a power of two.
  110. */
  111. private static final int DEFAULT_INITIAL_CAPACITY = 16;
  112. /**
  113. * The maximum capacity, used if a higher value is implicitly specified
  114. * by either of the constructors with arguments.
  115. * MUST be a power of two <= 1<<30.
  116. */
  117. private static final int MAXIMUM_CAPACITY = 1 << 30;
  118. /**
  119. * The load fast used when none specified in constructor.
  120. */
  121. private static final float DEFAULT_LOAD_FACTOR = 0.75f;
  122. /**
  123. * The table, resized as necessary. Length MUST Always be a power of two.
  124. */
  125. private Entry[] table;
  126. /**
  127. * The number of key-value mappings contained in this weak hash map.
  128. */
  129. private int size;
  130. /**
  131. * The next size value at which to resize (capacity * load factor).
  132. */
  133. private int threshold;
  134. /**
  135. * The load factor for the hash table.
  136. */
  137. private final float loadFactor;
  138. /**
  139. * Reference queue for cleared WeakEntries
  140. */
  141. private final ReferenceQueue<K> queue = new ReferenceQueue<K>();
  142. /**
  143. * The number of times this HashMap has been structurally modified
  144. * Structural modifications are those that change the number of mappings in
  145. * the HashMap or otherwise modify its internal structure (e.g.,
  146. * rehash). This field is used to make iterators on Collection-views of
  147. * the HashMap fail-fast. (See ConcurrentModificationException).
  148. */
  149. private volatile int modCount;
  150. /**
  151. * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
  152. * capacity and the given load factor.
  153. *
  154. * @param initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
  155. * @param loadFactor The load factor of the <tt>WeakHashMap</tt>
  156. * @throws IllegalArgumentException If the initial capacity is negative,
  157. * or if the load factor is nonpositive.
  158. */
  159. public WeakHashMap(int initialCapacity, float loadFactor) {
  160. if (initialCapacity < 0)
  161. throw new IllegalArgumentException("Illegal Initial Capacity: "+
  162. initialCapacity);
  163. if (initialCapacity > MAXIMUM_CAPACITY)
  164. initialCapacity = MAXIMUM_CAPACITY;
  165. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  166. throw new IllegalArgumentException("Illegal Load factor: "+
  167. loadFactor);
  168. int capacity = 1;
  169. while (capacity < initialCapacity)
  170. capacity <<= 1;
  171. table = new Entry[capacity];
  172. this.loadFactor = loadFactor;
  173. threshold = (int)(capacity * loadFactor);
  174. }
  175. /**
  176. * Constructs a new, empty <tt>WeakHashMap</tt> with the given initial
  177. * capacity and the default load factor, which is <tt>0.75</tt>.
  178. *
  179. * @param initialCapacity The initial capacity of the <tt>WeakHashMap</tt>
  180. * @throws IllegalArgumentException If the initial capacity is negative.
  181. */
  182. public WeakHashMap(int initialCapacity) {
  183. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  184. }
  185. /**
  186. * Constructs a new, empty <tt>WeakHashMap</tt> with the default initial
  187. * capacity (16) and the default load factor (0.75).
  188. */
  189. public WeakHashMap() {
  190. this.loadFactor = DEFAULT_LOAD_FACTOR;
  191. threshold = (int)(DEFAULT_INITIAL_CAPACITY);
  192. table = new Entry[DEFAULT_INITIAL_CAPACITY];
  193. }
  194. /**
  195. * Constructs a new <tt>WeakHashMap</tt> with the same mappings as the
  196. * specified <tt>Map</tt>. The <tt>WeakHashMap</tt> is created with
  197. * default load factor, which is <tt>0.75</tt> and an initial capacity
  198. * sufficient to hold the mappings in the specified <tt>Map</tt>.
  199. *
  200. * @param t the map whose mappings are to be placed in this map.
  201. * @throws NullPointerException if the specified map is null.
  202. * @since 1.3
  203. */
  204. public WeakHashMap(Map<? extends K, ? extends V> t) {
  205. this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1, 16),
  206. DEFAULT_LOAD_FACTOR);
  207. putAll(t);
  208. }
  209. // internal utilities
  210. /**
  211. * Value representing null keys inside tables.
  212. */
  213. private static final Object NULL_KEY = new Object();
  214. /**
  215. * Use NULL_KEY for key if it is null.
  216. */
  217. private static Object maskNull(Object key) {
  218. return (key == null ? NULL_KEY : key);
  219. }
  220. /**
  221. * Return internal representation of null key back to caller as null
  222. */
  223. private static <K> K unmaskNull(Object key) {
  224. return (K) (key == NULL_KEY ? null : key);
  225. }
  226. /**
  227. * Check for equality of non-null reference x and possibly-null y. By
  228. * default uses Object.equals.
  229. */
  230. static boolean eq(Object x, Object y) {
  231. return x == y || x.equals(y);
  232. }
  233. /**
  234. * Return index for hash code h.
  235. */
  236. static int indexFor(int h, int length) {
  237. return h & (length-1);
  238. }
  239. /**
  240. * Expunge stale entries from the table.
  241. */
  242. private void expungeStaleEntries() {
  243. Entry<K,V> e;
  244. while ( (e = (Entry<K,V>) queue.poll()) != null) {
  245. int h = e.hash;
  246. int i = indexFor(h, table.length);
  247. Entry<K,V> prev = table[i];
  248. Entry<K,V> p = prev;
  249. while (p != null) {
  250. Entry<K,V> next = p.next;
  251. if (p == e) {
  252. if (prev == e)
  253. table[i] = next;
  254. else
  255. prev.next = next;
  256. e.next = null; // Help GC
  257. e.value = null; // " "
  258. size--;
  259. break;
  260. }
  261. prev = p;
  262. p = next;
  263. }
  264. }
  265. }
  266. /**
  267. * Return the table after first expunging stale entries
  268. */
  269. private Entry[] getTable() {
  270. expungeStaleEntries();
  271. return table;
  272. }
  273. /**
  274. * Returns the number of key-value mappings in this map.
  275. * This result is a snapshot, and may not reflect unprocessed
  276. * entries that will be removed before next attempted access
  277. * because they are no longer referenced.
  278. */
  279. public int size() {
  280. if (size == 0)
  281. return 0;
  282. expungeStaleEntries();
  283. return size;
  284. }
  285. /**
  286. * Returns <tt>true</tt> if this map contains no key-value mappings.
  287. * This result is a snapshot, and may not reflect unprocessed
  288. * entries that will be removed before next attempted access
  289. * because they are no longer referenced.
  290. */
  291. public boolean isEmpty() {
  292. return size() == 0;
  293. }
  294. /**
  295. * Returns the value to which the specified key is mapped in this weak
  296. * hash map, or <tt>null</tt> if the map contains no mapping for
  297. * this key. A return value of <tt>null</tt> does not <i>necessarily</i>
  298. * indicate that the map contains no mapping for the key; it is also
  299. * possible that the map explicitly maps the key to <tt>null</tt>. The
  300. * <tt>containsKey</tt> method may be used to distinguish these two
  301. * cases.
  302. *
  303. * @param key the key whose associated value is to be returned.
  304. * @return the value to which this map maps the specified key, or
  305. * <tt>null</tt> if the map contains no mapping for this key.
  306. * @see #put(Object, Object)
  307. */
  308. public V get(Object key) {
  309. Object k = maskNull(key);
  310. int h = HashMap.hash(k);
  311. Entry[] tab = getTable();
  312. int index = indexFor(h, tab.length);
  313. Entry<K,V> e = tab[index];
  314. while (e != null) {
  315. if (e.hash == h && eq(k, e.get()))
  316. return e.value;
  317. e = e.next;
  318. }
  319. return null;
  320. }
  321. /**
  322. * Returns <tt>true</tt> if this map contains a mapping for the
  323. * specified key.
  324. *
  325. * @param key The key whose presence in this map is to be tested
  326. * @return <tt>true</tt> if there is a mapping for <tt>key</tt>
  327. * <tt>false</tt> otherwise
  328. */
  329. public boolean containsKey(Object key) {
  330. return getEntry(key) != null;
  331. }
  332. /**
  333. * Returns the entry associated with the specified key in the HashMap.
  334. * Returns null if the HashMap contains no mapping for this key.
  335. */
  336. Entry<K,V> getEntry(Object key) {
  337. Object k = maskNull(key);
  338. int h = HashMap.hash(k);
  339. Entry[] tab = getTable();
  340. int index = indexFor(h, tab.length);
  341. Entry<K,V> e = tab[index];
  342. while (e != null && !(e.hash == h && eq(k, e.get())))
  343. e = e.next;
  344. return e;
  345. }
  346. /**
  347. * Associates the specified value with the specified key in this map.
  348. * If the map previously contained a mapping for this key, the old
  349. * value is replaced.
  350. *
  351. * @param key key with which the specified value is to be associated.
  352. * @param value value to be associated with the specified key.
  353. * @return previous value associated with specified key, or <tt>null</tt>
  354. * if there was no mapping for key. A <tt>null</tt> return can
  355. * also indicate that the HashMap previously associated
  356. * <tt>null</tt> with the specified key.
  357. */
  358. public V put(K key, V value) {
  359. K k = (K) maskNull(key);
  360. int h = HashMap.hash(k);
  361. Entry[] tab = getTable();
  362. int i = indexFor(h, tab.length);
  363. for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
  364. if (h == e.hash && eq(k, e.get())) {
  365. V oldValue = e.value;
  366. if (value != oldValue)
  367. e.value = value;
  368. return oldValue;
  369. }
  370. }
  371. modCount++;
  372. Entry<K,V> e = tab[i];
  373. tab[i] = new Entry<K,V>(k, value, queue, h, e);
  374. if (++size >= threshold)
  375. resize(tab.length * 2);
  376. return null;
  377. }
  378. /**
  379. * Rehashes the contents of this map into a new array with a
  380. * larger capacity. This method is called automatically when the
  381. * number of keys in this map reaches its threshold.
  382. *
  383. * If current capacity is MAXIMUM_CAPACITY, this method does not
  384. * resize the map, but sets threshold to Integer.MAX_VALUE.
  385. * This has the effect of preventing future calls.
  386. *
  387. * @param newCapacity the new capacity, MUST be a power of two;
  388. * must be greater than current capacity unless current
  389. * capacity is MAXIMUM_CAPACITY (in which case value
  390. * is irrelevant).
  391. */
  392. void resize(int newCapacity) {
  393. Entry[] oldTable = getTable();
  394. int oldCapacity = oldTable.length;
  395. if (oldCapacity == MAXIMUM_CAPACITY) {
  396. threshold = Integer.MAX_VALUE;
  397. return;
  398. }
  399. Entry[] newTable = new Entry[newCapacity];
  400. transfer(oldTable, newTable);
  401. table = newTable;
  402. /*
  403. * If ignoring null elements and processing ref queue caused massive
  404. * shrinkage, then restore old table. This should be rare, but avoids
  405. * unbounded expansion of garbage-filled tables.
  406. */
  407. if (size >= threshold / 2) {
  408. threshold = (int)(newCapacity * loadFactor);
  409. } else {
  410. expungeStaleEntries();
  411. transfer(newTable, oldTable);
  412. table = oldTable;
  413. }
  414. }
  415. /** Transfer all entries from src to dest tables */
  416. private void transfer(Entry[] src, Entry[] dest) {
  417. for (int j = 0; j < src.length; ++j) {
  418. Entry<K,V> e = src[j];
  419. src[j] = null;
  420. while (e != null) {
  421. Entry<K,V> next = e.next;
  422. Object key = e.get();
  423. if (key == null) {
  424. e.next = null; // Help GC
  425. e.value = null; // " "
  426. size--;
  427. } else {
  428. int i = indexFor(e.hash, dest.length);
  429. e.next = dest[i];
  430. dest[i] = e;
  431. }
  432. e = next;
  433. }
  434. }
  435. }
  436. /**
  437. * Copies all of the mappings from the specified map to this map These
  438. * mappings will replace any mappings that this map had for any of the
  439. * keys currently in the specified map.<p>
  440. *
  441. * @param m mappings to be stored in this map.
  442. * @throws NullPointerException if the specified map is null.
  443. */
  444. public void putAll(Map<? extends K, ? extends V> m) {
  445. int numKeysToBeAdded = m.size();
  446. if (numKeysToBeAdded == 0)
  447. return;
  448. /*
  449. * Expand the map if the map if the number of mappings to be added
  450. * is greater than or equal to threshold. This is conservative; the
  451. * obvious condition is (m.size() + size) >= threshold, but this
  452. * condition could result in a map with twice the appropriate capacity,
  453. * if the keys to be added overlap with the keys already in this map.
  454. * By using the conservative calculation, we subject ourself
  455. * to at most one extra resize.
  456. */
  457. if (numKeysToBeAdded > threshold) {
  458. int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
  459. if (targetCapacity > MAXIMUM_CAPACITY)
  460. targetCapacity = MAXIMUM_CAPACITY;
  461. int newCapacity = table.length;
  462. while (newCapacity < targetCapacity)
  463. newCapacity <<= 1;
  464. if (newCapacity > table.length)
  465. resize(newCapacity);
  466. }
  467. for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
  468. Map.Entry<? extends K, ? extends V> e = i.next();
  469. put(e.getKey(), e.getValue());
  470. }
  471. }
  472. /**
  473. * Removes the mapping for this key from this map if present.
  474. *
  475. * @param key key whose mapping is to be removed from the map.
  476. * @return previous value associated with specified key, or <tt>null</tt>
  477. * if there was no mapping for key. A <tt>null</tt> return can
  478. * also indicate that the map previously associated <tt>null</tt>
  479. * with the specified key.
  480. */
  481. public V remove(Object key) {
  482. Object k = maskNull(key);
  483. int h = HashMap.hash(k);
  484. Entry[] tab = getTable();
  485. int i = indexFor(h, tab.length);
  486. Entry<K,V> prev = tab[i];
  487. Entry<K,V> e = prev;
  488. while (e != null) {
  489. Entry<K,V> next = e.next;
  490. if (h == e.hash && eq(k, e.get())) {
  491. modCount++;
  492. size--;
  493. if (prev == e)
  494. tab[i] = next;
  495. else
  496. prev.next = next;
  497. return e.value;
  498. }
  499. prev = e;
  500. e = next;
  501. }
  502. return null;
  503. }
  504. /** Special version of remove needed by Entry set */
  505. Entry<K,V> removeMapping(Object o) {
  506. if (!(o instanceof Map.Entry))
  507. return null;
  508. Entry[] tab = getTable();
  509. Map.Entry entry = (Map.Entry)o;
  510. Object k = maskNull(entry.getKey());
  511. int h = HashMap.hash(k);
  512. int i = indexFor(h, tab.length);
  513. Entry<K,V> prev = tab[i];
  514. Entry<K,V> e = prev;
  515. while (e != null) {
  516. Entry<K,V> next = e.next;
  517. if (h == e.hash && e.equals(entry)) {
  518. modCount++;
  519. size--;
  520. if (prev == e)
  521. tab[i] = next;
  522. else
  523. prev.next = next;
  524. return e;
  525. }
  526. prev = e;
  527. e = next;
  528. }
  529. return null;
  530. }
  531. /**
  532. * Removes all mappings from this map.
  533. */
  534. public void clear() {
  535. // clear out ref queue. We don't need to expunge entries
  536. // since table is getting cleared.
  537. while (queue.poll() != null)
  538. ;
  539. modCount++;
  540. Entry[] tab = table;
  541. for (int i = 0; i < tab.length; ++i)
  542. tab[i] = null;
  543. size = 0;
  544. // Allocation of array may have caused GC, which may have caused
  545. // additional entries to go stale. Removing these entries from the
  546. // reference queue will make them eligible for reclamation.
  547. while (queue.poll() != null)
  548. ;
  549. }
  550. /**
  551. * Returns <tt>true</tt> if this map maps one or more keys to the
  552. * specified value.
  553. *
  554. * @param value value whose presence in this map is to be tested.
  555. * @return <tt>true</tt> if this map maps one or more keys to the
  556. * specified value.
  557. */
  558. public boolean containsValue(Object value) {
  559. if (value==null)
  560. return containsNullValue();
  561. Entry[] tab = getTable();
  562. for (int i = tab.length ; i-- > 0 ;)
  563. for (Entry e = tab[i] ; e != null ; e = e.next)
  564. if (value.equals(e.value))
  565. return true;
  566. return false;
  567. }
  568. /**
  569. * Special-case code for containsValue with null argument
  570. */
  571. private boolean containsNullValue() {
  572. Entry[] tab = getTable();
  573. for (int i = tab.length ; i-- > 0 ;)
  574. for (Entry e = tab[i] ; e != null ; e = e.next)
  575. if (e.value==null)
  576. return true;
  577. return false;
  578. }
  579. /**
  580. * The entries in this hash table extend WeakReference, using its main ref
  581. * field as the key.
  582. */
  583. private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
  584. private V value;
  585. private final int hash;
  586. private Entry<K,V> next;
  587. /**
  588. * Create new entry.
  589. */
  590. Entry(K key, V value,
  591. ReferenceQueue<K> queue,
  592. int hash, Entry<K,V> next) {
  593. super(key, queue);
  594. this.value = value;
  595. this.hash = hash;
  596. this.next = next;
  597. }
  598. public K getKey() {
  599. return WeakHashMap.<K>unmaskNull(get());
  600. }
  601. public V getValue() {
  602. return value;
  603. }
  604. public V setValue(V newValue) {
  605. V oldValue = value;
  606. value = newValue;
  607. return oldValue;
  608. }
  609. public boolean equals(Object o) {
  610. if (!(o instanceof Map.Entry))
  611. return false;
  612. Map.Entry e = (Map.Entry)o;
  613. Object k1 = getKey();
  614. Object k2 = e.getKey();
  615. if (k1 == k2 || (k1 != null && k1.equals(k2))) {
  616. Object v1 = getValue();
  617. Object v2 = e.getValue();
  618. if (v1 == v2 || (v1 != null && v1.equals(v2)))
  619. return true;
  620. }
  621. return false;
  622. }
  623. public int hashCode() {
  624. Object k = getKey();
  625. Object v = getValue();
  626. return ((k==null ? 0 : k.hashCode()) ^
  627. (v==null ? 0 : v.hashCode()));
  628. }
  629. public String toString() {
  630. return getKey() + "=" + getValue();
  631. }
  632. }
  633. private abstract class HashIterator<T> implements Iterator<T> {
  634. int index;
  635. Entry<K,V> entry = null;
  636. Entry<K,V> lastReturned = null;
  637. int expectedModCount = modCount;
  638. /**
  639. * Strong reference needed to avoid disappearance of key
  640. * between hasNext and next
  641. */
  642. Object nextKey = null;
  643. /**
  644. * Strong reference needed to avoid disappearance of key
  645. * between nextEntry() and any use of the entry
  646. */
  647. Object currentKey = null;
  648. HashIterator() {
  649. index = (size() != 0 ? table.length : 0);
  650. }
  651. public boolean hasNext() {
  652. Entry[] t = table;
  653. while (nextKey == null) {
  654. Entry<K,V> e = entry;
  655. int i = index;
  656. while (e == null && i > 0)
  657. e = t[--i];
  658. entry = e;
  659. index = i;
  660. if (e == null) {
  661. currentKey = null;
  662. return false;
  663. }
  664. nextKey = e.get(); // hold on to key in strong ref
  665. if (nextKey == null)
  666. entry = entry.next;
  667. }
  668. return true;
  669. }
  670. /** The common parts of next() across different types of iterators */
  671. protected Entry<K,V> nextEntry() {
  672. if (modCount != expectedModCount)
  673. throw new ConcurrentModificationException();
  674. if (nextKey == null && !hasNext())
  675. throw new NoSuchElementException();
  676. lastReturned = entry;
  677. entry = entry.next;
  678. currentKey = nextKey;
  679. nextKey = null;
  680. return lastReturned;
  681. }
  682. public void remove() {
  683. if (lastReturned == null)
  684. throw new IllegalStateException();
  685. if (modCount != expectedModCount)
  686. throw new ConcurrentModificationException();
  687. WeakHashMap.this.remove(currentKey);
  688. expectedModCount = modCount;
  689. lastReturned = null;
  690. currentKey = null;
  691. }
  692. }
  693. private class ValueIterator extends HashIterator<V> {
  694. public V next() {
  695. return nextEntry().value;
  696. }
  697. }
  698. private class KeyIterator extends HashIterator<K> {
  699. public K next() {
  700. return nextEntry().getKey();
  701. }
  702. }
  703. private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
  704. public Map.Entry<K,V> next() {
  705. return nextEntry();
  706. }
  707. }
  708. // Views
  709. private transient Set<Map.Entry<K,V>> entrySet = null;
  710. /**
  711. * Returns a set view of the keys contained in this map. The set is
  712. * backed by the map, so changes to the map are reflected in the set, and
  713. * vice-versa. The set supports element removal, which removes the
  714. * corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
  715. * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
  716. * <tt>clear</tt> operations. It does not support the <tt>add</tt> or
  717. * <tt>addAll</tt> operations.
  718. *
  719. * @return a set view of the keys contained in this map.
  720. */
  721. public Set<K> keySet() {
  722. Set<K> ks = keySet;
  723. return (ks != null ? ks : (keySet = new KeySet()));
  724. }
  725. private class KeySet extends AbstractSet<K> {
  726. public Iterator<K> iterator() {
  727. return new KeyIterator();
  728. }
  729. public int size() {
  730. return WeakHashMap.this.size();
  731. }
  732. public boolean contains(Object o) {
  733. return containsKey(o);
  734. }
  735. public boolean remove(Object o) {
  736. if (containsKey(o)) {
  737. WeakHashMap.this.remove(o);
  738. return true;
  739. }
  740. else
  741. return false;
  742. }
  743. public void clear() {
  744. WeakHashMap.this.clear();
  745. }
  746. public Object[] toArray() {
  747. Collection<K> c = new ArrayList<K>(size());
  748. for (Iterator<K> i = iterator(); i.hasNext(); )
  749. c.add(i.next());
  750. return c.toArray();
  751. }
  752. public <T> T[] toArray(T[] a) {
  753. Collection<K> c = new ArrayList<K>(size());
  754. for (Iterator<K> i = iterator(); i.hasNext(); )
  755. c.add(i.next());
  756. return c.toArray(a);
  757. }
  758. }
  759. /**
  760. * Returns a collection view of the values contained in this map. The
  761. * collection is backed by the map, so changes to the map are reflected in
  762. * the collection, and vice-versa. The collection supports element
  763. * removal, which removes the corresponding mapping from this map, via the
  764. * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  765. * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
  766. * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
  767. *
  768. * @return a collection view of the values contained in this map.
  769. */
  770. public Collection<V> values() {
  771. Collection<V> vs = values;
  772. return (vs != null ? vs : (values = new Values()));
  773. }
  774. private class Values extends AbstractCollection<V> {
  775. public Iterator<V> iterator() {
  776. return new ValueIterator();
  777. }
  778. public int size() {
  779. return WeakHashMap.this.size();
  780. }
  781. public boolean contains(Object o) {
  782. return containsValue(o);
  783. }
  784. public void clear() {
  785. WeakHashMap.this.clear();
  786. }
  787. public Object[] toArray() {
  788. Collection<V> c = new ArrayList<V>(size());
  789. for (Iterator<V> i = iterator(); i.hasNext(); )
  790. c.add(i.next());
  791. return c.toArray();
  792. }
  793. public <T> T[] toArray(T[] a) {
  794. Collection<V> c = new ArrayList<V>(size());
  795. for (Iterator<V> i = iterator(); i.hasNext(); )
  796. c.add(i.next());
  797. return c.toArray(a);
  798. }
  799. }
  800. /**
  801. * Returns a collection view of the mappings contained in this map. Each
  802. * element in the returned collection is a <tt>Map.Entry</tt>. The
  803. * collection is backed by the map, so changes to the map are reflected in
  804. * the collection, and vice-versa. The collection supports element
  805. * removal, which removes the corresponding mapping from the map, via the
  806. * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  807. * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
  808. * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
  809. *
  810. * @return a collection view of the mappings contained in this map.
  811. * @see Map.Entry
  812. */
  813. public Set<Map.Entry<K,V>> entrySet() {
  814. Set<Map.Entry<K,V>> es = entrySet;
  815. return (es != null ? es : (entrySet = new EntrySet()));
  816. }
  817. private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
  818. public Iterator<Map.Entry<K,V>> iterator() {
  819. return new EntryIterator();
  820. }
  821. public boolean contains(Object o) {
  822. if (!(o instanceof Map.Entry))
  823. return false;
  824. Map.Entry e = (Map.Entry)o;
  825. Object k = e.getKey();
  826. Entry candidate = getEntry(e.getKey());
  827. return candidate != null && candidate.equals(e);
  828. }
  829. public boolean remove(Object o) {
  830. return removeMapping(o) != null;
  831. }
  832. public int size() {
  833. return WeakHashMap.this.size();
  834. }
  835. public void clear() {
  836. WeakHashMap.this.clear();
  837. }
  838. public Object[] toArray() {
  839. Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
  840. for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
  841. c.add(new AbstractMap.SimpleEntry<K,V>(i.next()));
  842. return c.toArray();
  843. }
  844. public <T> T[] toArray(T[] a) {
  845. Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
  846. for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
  847. c.add(new AbstractMap.SimpleEntry<K,V>(i.next()));
  848. return c.toArray(a);
  849. }
  850. }
  851. }