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