1. /*
  2. * @(#)IdentityHashMap.java 1.22 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. * This class implements the <tt>Map</tt> interface with a hash table, using
  11. * reference-equality in place of object-equality when comparing keys (and
  12. * values). In other words, in an <tt>IdentityHashMap</tt>, two keys
  13. * <tt>k1</tt> and <tt>k2</tt> are considered equal if and only if
  14. * <tt>(k1==k2)</tt>. (In normal <tt>Map</tt> implementations (like
  15. * <tt>HashMap</tt>) two keys <tt>k1</tt> and <tt>k2</tt> are considered equal
  16. * if and only if <tt>(k1==null ? k2==null : k1.equals(k2))</tt>.)
  17. *
  18. * <p><b>This class is <i>not</i> a general-purpose <tt>Map</tt>
  19. * implementation! While this class implements the <tt>Map</tt> interface, it
  20. * intentionally violates <tt>Map's</tt> general contract, which mandates the
  21. * use of the <tt>equals</tt> method when comparing objects. This class is
  22. * designed for use only in the rare cases wherein reference-equality
  23. * semantics are required.</b>
  24. *
  25. * <p>A typical use of this class is <i>topology-preserving object graph
  26. * transformations</i>, such as serialization or deep-copying. To perform such
  27. * a transformation, a program must maintain a "node table" that keeps track
  28. * of all the object references that have already been processed. The node
  29. * table must not equate distinct objects even if they happen to be equal.
  30. * Another typical use of this class is to maintain <i>proxy objects</i>. For
  31. * example, a debugging facility might wish to maintain a proxy object for
  32. * each object in the program being debugged.
  33. *
  34. * <p>This class provides all of the optional map operations, and permits
  35. * <tt>null</tt> values and the <tt>null</tt> key. This class makes no
  36. * guarantees as to the order of the map; in particular, it does not guarantee
  37. * that the order will remain constant over time.
  38. *
  39. * <p>This class provides constant-time performance for the basic
  40. * operations (<tt>get</tt> and <tt>put</tt>), assuming the system
  41. * identity hash function ({@link System#identityHashCode(Object)})
  42. * disperses elements properly among the buckets.
  43. *
  44. * <p>This class has one tuning parameter (which affects performance but not
  45. * semantics): <i>expected maximum size</i>. This parameter is the maximum
  46. * number of key-value mappings that the map is expected to hold. Internally,
  47. * this parameter is used to determine the number of buckets initially
  48. * comprising the hash table. The precise relationship between the expected
  49. * maximum size and the number of buckets is unspecified.
  50. *
  51. * <p>If the size of the map (the number of key-value mappings) sufficiently
  52. * exceeds the expected maximum size, the number of buckets is increased
  53. * Increasing the number of buckets ("rehashing") may be fairly expensive, so
  54. * it pays to create identity hash maps with a sufficiently large expected
  55. * maximum size. On the other hand, iteration over collection views requires
  56. * time proportional to the number of buckets in the hash table, so it
  57. * pays not to set the expected maximum size too high if you are especially
  58. * concerned with iteration performance or memory usage.
  59. *
  60. * <p><b>Note that this implementation is not synchronized.</b> If multiple
  61. * threads access this map concurrently, and at least one of the threads
  62. * modifies the map structurally, it <i>must</i> be synchronized externally.
  63. * (A structural modification is any operation that adds or deletes one or
  64. * more mappings; merely changing the value associated with a key that an
  65. * instance already contains is not a structural modification.) This is
  66. * typically accomplished by synchronizing on some object that naturally
  67. * encapsulates the map. If no such object exists, the map should be
  68. * "wrapped" using the <tt>Collections.synchronizedMap</tt> method. This is
  69. * best done at creation time, to prevent accidental unsynchronized access to
  70. * the map: <pre>
  71. * Map m = Collections.synchronizedMap(new HashMap(...));
  72. * </pre>
  73. *
  74. * <p>The iterators returned by all of this class's "collection view methods"
  75. * are <i>fail-fast</i>: if the map is structurally modified at any time after
  76. * the iterator is created, in any way except through the iterator's own
  77. * <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
  78. * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
  79. * modification, the iterator fails quickly and cleanly, rather than risking
  80. * arbitrary, non-deterministic behavior at an undetermined time in the
  81. * future.
  82. *
  83. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  84. * as it is, generally speaking, impossible to make any hard guarantees in the
  85. * presence of unsynchronized concurrent modification. Fail-fast iterators
  86. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  87. * Therefore, it would be wrong to write a program that depended on this
  88. * exception for its correctness: <i>fail-fast iterators should be used only
  89. * to detect bugs.</i>
  90. *
  91. * <p>Implementation note: This is a simple <i>linear-probe</i> hash table,
  92. * as described for example in texts by Sedgewick and Knuth. The array
  93. * alternates holding keys and values. (This has better locality for large
  94. * tables than does using separate arrays.) For many JRE implementations
  95. * and operation mixes, this class will yield better performance than
  96. * {@link HashMap} (which uses <i>chaining</i> rather than linear-probing).
  97. *
  98. * <p>This class is a member of the
  99. * <a href="{@docRoot}/../guide/collections/index.html">
  100. * Java Collections Framework</a>.
  101. *
  102. * @see System#identityHashCode(Object)
  103. * @see Object#hashCode()
  104. * @see Collection
  105. * @see Map
  106. * @see HashMap
  107. * @see TreeMap
  108. * @author Doug Lea and Josh Bloch
  109. * @since 1.4
  110. */
  111. public class IdentityHashMap<K,V>
  112. extends AbstractMap<K,V>
  113. implements Map<K,V>, java.io.Serializable, Cloneable
  114. {
  115. /**
  116. * The initial capacity used by the no-args constructor.
  117. * MUST be a power of two. The value 32 corresponds to the
  118. * (specified) expected maximum size of 21, given a load factor
  119. * of 2/3.
  120. */
  121. private static final int DEFAULT_CAPACITY = 32;
  122. /**
  123. * The minimum capacity, used if a lower value is implicitly specified
  124. * by either of the constructors with arguments. The value 4 corresponds
  125. * to an expected maximum size of 2, given a load factor of 2/3.
  126. * MUST be a power of two.
  127. */
  128. private static final int MINIMUM_CAPACITY = 4;
  129. /**
  130. * The maximum capacity, used if a higher value is implicitly specified
  131. * by either of the constructors with arguments.
  132. * MUST be a power of two <= 1<<29.
  133. */
  134. private static final int MAXIMUM_CAPACITY = 1 << 29;
  135. /**
  136. * The table, resized as necessary. Length MUST always be a power of two.
  137. */
  138. private transient Object[] table;
  139. /**
  140. * The number of key-value mappings contained in this identity hash map.
  141. *
  142. * @serial
  143. */
  144. private int size;
  145. /**
  146. * The number of modifications, to support fast-fail iterators
  147. */
  148. private transient volatile int modCount;
  149. /**
  150. * The next size value at which to resize (capacity * load factor).
  151. */
  152. private transient int threshold;
  153. /**
  154. * Value representing null keys inside tables.
  155. */
  156. private static final Object NULL_KEY = new Object();
  157. /**
  158. * Use NULL_KEY for key if it is null.
  159. */
  160. private static Object maskNull(Object key) {
  161. return (key == null ? NULL_KEY : key);
  162. }
  163. /**
  164. * Return internal representation of null key back to caller as null
  165. */
  166. private static Object unmaskNull(Object key) {
  167. return (key == NULL_KEY ? null : key);
  168. }
  169. /**
  170. * Constructs a new, empty identity hash map with a default expected
  171. * maximum size (21).
  172. */
  173. public IdentityHashMap() {
  174. init(DEFAULT_CAPACITY);
  175. }
  176. /**
  177. * Constructs a new, empty map with the specified expected maximum size.
  178. * Putting more than the expected number of key-value mappings into
  179. * the map may cause the internal data structure to grow, which may be
  180. * somewhat time-consuming.
  181. *
  182. * @param expectedMaxSize the expected maximum size of the map.
  183. * @throws IllegalArgumentException if <tt>expectedMaxSize</tt> is negative
  184. */
  185. public IdentityHashMap(int expectedMaxSize) {
  186. if (expectedMaxSize < 0)
  187. throw new IllegalArgumentException("expectedMaxSize is negative: "
  188. + expectedMaxSize);
  189. init(capacity(expectedMaxSize));
  190. }
  191. /**
  192. * Returns the appropriate capacity for the specified expected maximum
  193. * size. Returns the smallest power of two between MINIMUM_CAPACITY
  194. * and MAXIMUM_CAPACITY, inclusive, that is greater than
  195. * (3 * expectedMaxSize)/2, if such a number exists. Otherwise
  196. * returns MAXIMUM_CAPACITY. If (3 * expectedMaxSize)/2 is negative, it
  197. * is assumed that overflow has occurred, and MAXIMUM_CAPACITY is returned.
  198. */
  199. private int capacity(int expectedMaxSize) {
  200. // Compute min capacity for expectedMaxSize given a load factor of 2/3
  201. int minCapacity = (3 * expectedMaxSize)/2;
  202. // Compute the appropriate capacity
  203. int result;
  204. if (minCapacity > MAXIMUM_CAPACITY || minCapacity < 0) {
  205. result = MAXIMUM_CAPACITY;
  206. } else {
  207. result = MINIMUM_CAPACITY;
  208. while (result < minCapacity)
  209. result <<= 1;
  210. }
  211. return result;
  212. }
  213. /**
  214. * Initialize object to be an empty map with the specified initial
  215. * capacity, which is assumed to be a power of two between
  216. * MINIMUM_CAPACITY and MAXIMUM_CAPACITY inclusive.
  217. */
  218. private void init(int initCapacity) {
  219. // assert (initCapacity & -initCapacity) == initCapacity; // power of 2
  220. // assert initCapacity >= MINIMUM_CAPACITY;
  221. // assert initCapacity <= MAXIMUM_CAPACITY;
  222. threshold = (initCapacity * 2)/3;
  223. table = new Object[2 * initCapacity];
  224. }
  225. /**
  226. * Constructs a new identity hash map containing the keys-value mappings
  227. * in the specified map.
  228. *
  229. * @param m the map whose mappings are to be placed into this map.
  230. * @throws NullPointerException if the specified map is null.
  231. */
  232. public IdentityHashMap(Map<? extends K, ? extends V> m) {
  233. // Allow for a bit of growth
  234. this((int) ((1 + m.size()) * 1.1));
  235. putAll(m);
  236. }
  237. /**
  238. * Returns the number of key-value mappings in this identity hash map.
  239. *
  240. * @return the number of key-value mappings in this map.
  241. */
  242. public int size() {
  243. return size;
  244. }
  245. /**
  246. * Returns <tt>true</tt> if this identity hash map contains no key-value
  247. * mappings.
  248. *
  249. * @return <tt>true</tt> if this identity hash map contains no key-value
  250. * mappings.
  251. */
  252. public boolean isEmpty() {
  253. return size == 0;
  254. }
  255. /**
  256. * Return index for Object x.
  257. */
  258. private static int hash(Object x, int length) {
  259. int h = System.identityHashCode(x);
  260. // Multiply by -127, and left-shift to use least bit as part of hash
  261. return ((h << 1) - (h << 8)) & (length - 1);
  262. }
  263. /**
  264. * Circularly traverse table of size len.
  265. **/
  266. private static int nextKeyIndex(int i, int len) {
  267. return (i + 2 < len ? i + 2 : 0);
  268. }
  269. /**
  270. * Returns the value to which the specified key is mapped in this identity
  271. * hash map, or <tt>null</tt> if the map contains no mapping for
  272. * this key. A return value of <tt>null</tt> does not <i>necessarily</i>
  273. * indicate that the map contains no mapping for the key; it is also
  274. * possible that the map explicitly maps the key to <tt>null</tt>. The
  275. * <tt>containsKey</tt> method may be used to distinguish these two
  276. * cases.
  277. *
  278. * @param key the key whose associated value is to be returned.
  279. * @return the value to which this map maps the specified key, or
  280. * <tt>null</tt> if the map contains no mapping for this key.
  281. * @see #put(Object, Object)
  282. */
  283. public V get(Object key) {
  284. Object k = maskNull(key);
  285. Object[] tab = table;
  286. int len = tab.length;
  287. int i = hash(k, len);
  288. while (true) {
  289. Object item = tab[i];
  290. if (item == k)
  291. return (V) tab[i + 1];
  292. if (item == null)
  293. return null;
  294. i = nextKeyIndex(i, len);
  295. }
  296. }
  297. /**
  298. * Tests whether the specified object reference is a key in this identity
  299. * hash map.
  300. *
  301. * @param key possible key.
  302. * @return <code>true</code> if the specified object reference is a key
  303. * in this map.
  304. * @see #containsValue(Object)
  305. */
  306. public boolean containsKey(Object key) {
  307. Object k = maskNull(key);
  308. Object[] tab = table;
  309. int len = tab.length;
  310. int i = hash(k, len);
  311. while (true) {
  312. Object item = tab[i];
  313. if (item == k)
  314. return true;
  315. if (item == null)
  316. return false;
  317. i = nextKeyIndex(i, len);
  318. }
  319. }
  320. /**
  321. * Tests whether the specified object reference is a value in this identity
  322. * hash map.
  323. *
  324. * @param value value whose presence in this map is to be tested.
  325. * @return <tt>true</tt> if this map maps one or more keys to the
  326. * specified object reference.
  327. * @see #containsKey(Object)
  328. */
  329. public boolean containsValue(Object value) {
  330. Object[] tab = table;
  331. for (int i = 1; i < tab.length; i+= 2)
  332. if (tab[i] == value)
  333. return true;
  334. return false;
  335. }
  336. /**
  337. * Tests if the specified key-value mapping is in the map.
  338. *
  339. * @param key possible key.
  340. * @param value possible value.
  341. * @return <code>true</code> if and only if the specified key-value
  342. * mapping is in map.
  343. */
  344. private boolean containsMapping(Object key, Object value) {
  345. Object k = maskNull(key);
  346. Object[] tab = table;
  347. int len = tab.length;
  348. int i = hash(k, len);
  349. while (true) {
  350. Object item = tab[i];
  351. if (item == k)
  352. return tab[i + 1] == value;
  353. if (item == null)
  354. return false;
  355. i = nextKeyIndex(i, len);
  356. }
  357. }
  358. /**
  359. * Associates the specified value with the specified key in this identity
  360. * hash map. If the map previously contained a mapping for this key, the
  361. * old value is replaced.
  362. *
  363. * @param key the key with which the specified value is to be associated.
  364. * @param value the value to be associated with the specified key.
  365. * @return the previous value associated with <tt>key</tt>, or
  366. * <tt>null</tt> if there was no mapping for <tt>key</tt>. (A
  367. * <tt>null</tt> return can also indicate that the map previously
  368. * associated <tt>null</tt> with the specified key.)
  369. * @see Object#equals(Object)
  370. * @see #get(Object)
  371. * @see #containsKey(Object)
  372. */
  373. public V put(K key, V value) {
  374. Object k = maskNull(key);
  375. Object[] tab = table;
  376. int len = tab.length;
  377. int i = hash(k, len);
  378. Object item;
  379. while ( (item = tab[i]) != null) {
  380. if (item == k) {
  381. V oldValue = (V) tab[i + 1];
  382. tab[i + 1] = value;
  383. return oldValue;
  384. }
  385. i = nextKeyIndex(i, len);
  386. }
  387. modCount++;
  388. tab[i] = k;
  389. tab[i + 1] = value;
  390. if (++size >= threshold)
  391. resize(len); // len == 2 * current capacity.
  392. return null;
  393. }
  394. /**
  395. * Resize the table to hold given capacity.
  396. *
  397. * @param newCapacity the new capacity, must be a power of two.
  398. */
  399. private void resize(int newCapacity) {
  400. // assert (newCapacity & -newCapacity) == newCapacity; // power of 2
  401. int newLength = newCapacity * 2;
  402. Object[] oldTable = table;
  403. int oldLength = oldTable.length;
  404. if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further
  405. if (threshold == MAXIMUM_CAPACITY-1)
  406. throw new IllegalStateException("Capacity exhausted.");
  407. threshold = MAXIMUM_CAPACITY-1; // Gigantic map!
  408. return;
  409. }
  410. if (oldLength >= newLength)
  411. return;
  412. Object[] newTable = new Object[newLength];
  413. threshold = newLength / 3;
  414. for (int j = 0; j < oldLength; j += 2) {
  415. Object key = oldTable[j];
  416. if (key != null) {
  417. Object value = oldTable[j+1];
  418. oldTable[j] = null;
  419. oldTable[j+1] = null;
  420. int i = hash(key, newLength);
  421. while (newTable[i] != null)
  422. i = nextKeyIndex(i, newLength);
  423. newTable[i] = key;
  424. newTable[i + 1] = value;
  425. }
  426. }
  427. table = newTable;
  428. }
  429. /**
  430. * Copies all of the mappings from the specified map to this map
  431. * These mappings will replace any mappings that
  432. * this map had for any of the keys currently in the specified map.<p>
  433. *
  434. * @param t mappings to be stored in this map.
  435. * @throws NullPointerException if the specified map is null.
  436. */
  437. public void putAll(Map<? extends K, ? extends V> t) {
  438. int n = t.size();
  439. if (n == 0)
  440. return;
  441. if (n > threshold) // conservatively pre-expand
  442. resize(capacity(n));
  443. for (Entry<? extends K, ? extends V> e : t.entrySet())
  444. put(e.getKey(), e.getValue());
  445. }
  446. /**
  447. * Removes the mapping for this key from this map if present.
  448. *
  449. * @param key key whose mapping is to be removed from the map.
  450. * @return previous value associated with specified key, or <tt>null</tt>
  451. * if there was no entry for key. (A <tt>null</tt> return can
  452. * also indicate that the map previously associated <tt>null</tt>
  453. * with the specified key.)
  454. */
  455. public V remove(Object key) {
  456. Object k = maskNull(key);
  457. Object[] tab = table;
  458. int len = tab.length;
  459. int i = hash(k, len);
  460. while (true) {
  461. Object item = tab[i];
  462. if (item == k) {
  463. modCount++;
  464. size--;
  465. V oldValue = (V) tab[i + 1];
  466. tab[i + 1] = null;
  467. tab[i] = null;
  468. closeDeletion(i);
  469. return oldValue;
  470. }
  471. if (item == null)
  472. return null;
  473. i = nextKeyIndex(i, len);
  474. }
  475. }
  476. /**
  477. * Removes the specified key-value mapping from the map if it is present.
  478. *
  479. * @param key possible key.
  480. * @param value possible value.
  481. * @return <code>true</code> if and only if the specified key-value
  482. * mapping was in map.
  483. */
  484. private boolean removeMapping(Object key, Object value) {
  485. Object k = maskNull(key);
  486. Object[] tab = table;
  487. int len = tab.length;
  488. int i = hash(k, len);
  489. while (true) {
  490. Object item = tab[i];
  491. if (item == k) {
  492. if (tab[i + 1] != value)
  493. return false;
  494. modCount++;
  495. size--;
  496. tab[i] = null;
  497. tab[i + 1] = null;
  498. closeDeletion(i);
  499. return true;
  500. }
  501. if (item == null)
  502. return false;
  503. i = nextKeyIndex(i, len);
  504. }
  505. }
  506. /**
  507. * Rehash all possibly-colliding entries following a
  508. * deletion. This preserves the linear-probe
  509. * collision properties required by get, put, etc.
  510. *
  511. * @param d the index of a newly empty deleted slot
  512. */
  513. private void closeDeletion(int d) {
  514. // Adapted from Knuth Section 6.4 Algorithm R
  515. Object[] tab = table;
  516. int len = tab.length;
  517. // Look for items to swap into newly vacated slot
  518. // starting at index immediately following deletion,
  519. // and continuing until a null slot is seen, indicating
  520. // the end of a run of possibly-colliding keys.
  521. Object item;
  522. for (int i = nextKeyIndex(d, len); (item = tab[i]) != null;
  523. i = nextKeyIndex(i, len) ) {
  524. // The following test triggers if the item at slot i (which
  525. // hashes to be at slot r) should take the spot vacated by d.
  526. // If so, we swap it in, and then continue with d now at the
  527. // newly vacated i. This process will terminate when we hit
  528. // the null slot at the end of this run.
  529. // The test is messy because we are using a circular table.
  530. int r = hash(item, len);
  531. if ((i < r && (r <= d || d <= i)) || (r <= d && d <= i)) {
  532. tab[d] = item;
  533. tab[d + 1] = tab[i + 1];
  534. tab[i] = null;
  535. tab[i + 1] = null;
  536. d = i;
  537. }
  538. }
  539. }
  540. /**
  541. * Removes all mappings from this map.
  542. */
  543. public void clear() {
  544. modCount++;
  545. Object[] tab = table;
  546. for (int i = 0; i < tab.length; i++)
  547. tab[i] = null;
  548. size = 0;
  549. }
  550. /**
  551. * Compares the specified object with this map for equality. Returns
  552. * <tt>true</tt> if the given object is also a map and the two maps
  553. * represent identical object-reference mappings. More formally, this
  554. * map is equal to another map <tt>m</tt> if and only if
  555. * map <tt>this.entrySet().equals(m.entrySet())</tt>.
  556. *
  557. * <p><b>Owing to the reference-equality-based semantics of this map it is
  558. * possible that the symmetry and transitivity requirements of the
  559. * <tt>Object.equals</tt> contract may be violated if this map is compared
  560. * to a normal map. However, the <tt>Object.equals</tt> contract is
  561. * guaranteed to hold among <tt>IdentityHashMap</tt> instances.</b>
  562. *
  563. * @param o object to be compared for equality with this map.
  564. * @return <tt>true</tt> if the specified object is equal to this map.
  565. * @see Object#equals(Object)
  566. */
  567. public boolean equals(Object o) {
  568. if (o == this) {
  569. return true;
  570. } else if (o instanceof IdentityHashMap) {
  571. IdentityHashMap m = (IdentityHashMap) o;
  572. if (m.size() != size)
  573. return false;
  574. Object[] tab = m.table;
  575. for (int i = 0; i < tab.length; i+=2) {
  576. Object k = tab[i];
  577. if (k != null && !containsMapping(k, tab[i + 1]))
  578. return false;
  579. }
  580. return true;
  581. } else if (o instanceof Map) {
  582. Map m = (Map)o;
  583. return entrySet().equals(m.entrySet());
  584. } else {
  585. return false; // o is not a Map
  586. }
  587. }
  588. /**
  589. * Returns the hash code value for this map. The hash code of a map
  590. * is defined to be the sum of the hashcode of each entry in the map's
  591. * entrySet view. This ensures that <tt>t1.equals(t2)</tt> implies
  592. * that <tt>t1.hashCode()==t2.hashCode()</tt> for any two
  593. * <tt>IdentityHashMap</tt> instances <tt>t1</tt> and <tt>t2</tt>, as
  594. * required by the general contract of {@link Object#hashCode()}.
  595. *
  596. * <p><b>Owing to the reference-equality-based semantics of the
  597. * <tt>Map.Entry</tt> instances in the set returned by this map's
  598. * <tt>entrySet</tt> method, it is possible that the contractual
  599. * requirement of <tt>Object.hashCode</tt> mentioned in the previous
  600. * paragraph will be violated if one of the two objects being compared is
  601. * an <tt>IdentityHashMap</tt> instance and the other is a normal map.</b>
  602. *
  603. * @return the hash code value for this map.
  604. * @see Object#hashCode()
  605. * @see Object#equals(Object)
  606. * @see #equals(Object)
  607. */
  608. public int hashCode() {
  609. int result = 0;
  610. Object[] tab = table;
  611. for (int i = 0; i < tab.length; i +=2) {
  612. Object key = tab[i];
  613. if (key != null) {
  614. Object k = unmaskNull(key);
  615. result += System.identityHashCode(k) ^
  616. System.identityHashCode(tab[i + 1]);
  617. }
  618. }
  619. return result;
  620. }
  621. /**
  622. * Returns a shallow copy of this identity hash map: the keys and values
  623. * themselves are not cloned.
  624. *
  625. * @return a shallow copy of this map.
  626. */
  627. public Object clone() {
  628. try {
  629. IdentityHashMap<K,V> t = (IdentityHashMap<K,V>) super.clone();
  630. t.entrySet = null;
  631. t.table = (Object[])table.clone();
  632. return t;
  633. } catch (CloneNotSupportedException e) {
  634. throw new InternalError();
  635. }
  636. }
  637. private abstract class IdentityHashMapIterator<T> implements Iterator<T> {
  638. int index = (size != 0 ? 0 : table.length); // current slot.
  639. int expectedModCount = modCount; // to support fast-fail
  640. int lastReturnedIndex = -1; // to allow remove()
  641. boolean indexValid; // To avoid unnecessary next computation
  642. Object[] traversalTable = table; // reference to main table or copy
  643. public boolean hasNext() {
  644. Object[] tab = traversalTable;
  645. for (int i = index; i < tab.length; i+=2) {
  646. Object key = tab[i];
  647. if (key != null) {
  648. index = i;
  649. return indexValid = true;
  650. }
  651. }
  652. index = tab.length;
  653. return false;
  654. }
  655. protected int nextIndex() {
  656. if (modCount != expectedModCount)
  657. throw new ConcurrentModificationException();
  658. if (!indexValid && !hasNext())
  659. throw new NoSuchElementException();
  660. indexValid = false;
  661. lastReturnedIndex = index;
  662. index += 2;
  663. return lastReturnedIndex;
  664. }
  665. public void remove() {
  666. if (lastReturnedIndex == -1)
  667. throw new IllegalStateException();
  668. if (modCount != expectedModCount)
  669. throw new ConcurrentModificationException();
  670. expectedModCount = ++modCount;
  671. int deletedSlot = lastReturnedIndex;
  672. lastReturnedIndex = -1;
  673. size--;
  674. // back up index to revisit new contents after deletion
  675. index = deletedSlot;
  676. indexValid = false;
  677. // Removal code proceeds as in closeDeletion except that
  678. // it must catch the rare case where an element already
  679. // seen is swapped into a vacant slot that will be later
  680. // traversed by this iterator. We cannot allow future
  681. // next() calls to return it again. The likelihood of
  682. // this occurring under 2/3 load factor is very slim, but
  683. // when it does happen, we must make a copy of the rest of
  684. // the table to use for the rest of the traversal. Since
  685. // this can only happen when we are near the end of the table,
  686. // even in these rare cases, this is not very expensive in
  687. // time or space.
  688. Object[] tab = traversalTable;
  689. int len = tab.length;
  690. int d = deletedSlot;
  691. K key = (K) tab[d];
  692. tab[d] = null; // vacate the slot
  693. tab[d + 1] = null;
  694. // If traversing a copy, remove in real table.
  695. // We can skip gap-closure on copy.
  696. if (tab != IdentityHashMap.this.table) {
  697. IdentityHashMap.this.remove(key);
  698. expectedModCount = modCount;
  699. return;
  700. }
  701. Object item;
  702. for (int i = nextKeyIndex(d, len); (item = tab[i]) != null;
  703. i = nextKeyIndex(i, len)) {
  704. int r = hash(item, len);
  705. // See closeDeletion for explanation of this conditional
  706. if ((i < r && (r <= d || d <= i)) ||
  707. (r <= d && d <= i)) {
  708. // If we are about to swap an already-seen element
  709. // into a slot that may later be returned by next(),
  710. // then clone the rest of table for use in future
  711. // next() calls. It is OK that our copy will have
  712. // a gap in the "wrong" place, since it will never
  713. // be used for searching anyway.
  714. if (i < deletedSlot && d >= deletedSlot &&
  715. traversalTable == IdentityHashMap.this.table) {
  716. int remaining = len - deletedSlot;
  717. Object[] newTable = new Object[remaining];
  718. System.arraycopy(tab, deletedSlot,
  719. newTable, 0, remaining);
  720. traversalTable = newTable;
  721. index = 0;
  722. }
  723. tab[d] = item;
  724. tab[d + 1] = tab[i + 1];
  725. tab[i] = null;
  726. tab[i + 1] = null;
  727. d = i;
  728. }
  729. }
  730. }
  731. }
  732. private class KeyIterator extends IdentityHashMapIterator<K> {
  733. public K next() {
  734. return (K) unmaskNull(traversalTable[nextIndex()]);
  735. }
  736. }
  737. private class ValueIterator extends IdentityHashMapIterator<V> {
  738. public V next() {
  739. return (V) traversalTable[nextIndex() + 1];
  740. }
  741. }
  742. /**
  743. * Since we don't use Entry objects, we use the Iterator
  744. * itself as an entry.
  745. */
  746. private class EntryIterator
  747. extends IdentityHashMapIterator<Map.Entry<K,V>>
  748. implements Map.Entry<K,V>
  749. {
  750. public Map.Entry<K,V> next() {
  751. nextIndex();
  752. return this;
  753. }
  754. public K getKey() {
  755. // Provide a better exception than out of bounds index
  756. if (lastReturnedIndex < 0)
  757. throw new IllegalStateException("Entry was removed");
  758. return (K) unmaskNull(traversalTable[lastReturnedIndex]);
  759. }
  760. public V getValue() {
  761. // Provide a better exception than out of bounds index
  762. if (lastReturnedIndex < 0)
  763. throw new IllegalStateException("Entry was removed");
  764. return (V) traversalTable[lastReturnedIndex+1];
  765. }
  766. public V setValue(V value) {
  767. // It would be mean-spirited to proceed here if remove() called
  768. if (lastReturnedIndex < 0)
  769. throw new IllegalStateException("Entry was removed");
  770. V oldValue = (V) traversalTable[lastReturnedIndex+1];
  771. traversalTable[lastReturnedIndex+1] = value;
  772. // if shadowing, force into main table
  773. if (traversalTable != IdentityHashMap.this.table)
  774. put((K) traversalTable[lastReturnedIndex], value);
  775. return oldValue;
  776. }
  777. public boolean equals(Object o) {
  778. if (lastReturnedIndex < 0)
  779. return super.equals(o);
  780. if (!(o instanceof Map.Entry))
  781. return false;
  782. Map.Entry e = (Map.Entry)o;
  783. return e.getKey() == getKey() &&
  784. e.getValue() == getValue();
  785. }
  786. public int hashCode() {
  787. if (lastReturnedIndex < 0)
  788. return super.hashCode();
  789. return System.identityHashCode(getKey()) ^
  790. System.identityHashCode(getValue());
  791. }
  792. public String toString() {
  793. if (lastReturnedIndex < 0)
  794. return super.toString();
  795. return getKey() + "=" + getValue();
  796. }
  797. }
  798. // Views
  799. /**
  800. * This field is initialized to contain an instance of the entry set
  801. * view the first time this view is requested. The view is stateless,
  802. * so there's no reason to create more than one.
  803. */
  804. private transient Set<Map.Entry<K,V>> entrySet = null;
  805. /**
  806. * Returns an identity-based set view of the keys contained in this map.
  807. * The set is backed by the map, so changes to the map are reflected in
  808. * the set, and vice-versa. If the map is modified while an iteration
  809. * over the set is in progress, the results of the iteration are
  810. * undefined. The set supports element removal, which removes the
  811. * corresponding mapping from the map, via the <tt>Iterator.remove</tt>,
  812. * <tt>Set.remove</tt>, <tt>removeAll</tt> <tt>retainAll</tt>, and
  813. * <tt>clear</tt> methods. It does not support the <tt>add</tt> or
  814. * <tt>addAll</tt> methods.
  815. *
  816. * <p><b>While the object returned by this method implements the
  817. * <tt>Set</tt> interface, it does <i>not</i> obey <tt>Set's</tt> general
  818. * contract. Like its backing map, the set returned by this method
  819. * defines element equality as reference-equality rather than
  820. * object-equality. This affects the behavior of its <tt>contains</tt>,
  821. * <tt>remove</tt>, <tt>containsAll</tt>, <tt>equals</tt>, and
  822. * <tt>hashCode</tt> methods.</b>
  823. *
  824. * <p>The <tt>equals</tt> method of the returned set returns <tt>true</tt>
  825. * only if the specified object is a set containing exactly the same
  826. * object references as the returned set. The symmetry and transitivity
  827. * requirements of the <tt>Object.equals</tt> contract may be violated if
  828. * the set returned by this method is compared to a normal set. However,
  829. * the <tt>Object.equals</tt> contract is guaranteed to hold among sets
  830. * returned by this method.</b>
  831. *
  832. * <p>The <tt>hashCode</tt> method of the returned set returns the sum of
  833. * the <i>identity hashcodes</i> of the elements in the set, rather than
  834. * the sum of their hashcodes. This is mandated by the change in the
  835. * semantics of the <tt>equals</tt> method, in order to enforce the
  836. * general contract of the <tt>Object.hashCode</tt> method among sets
  837. * returned by this method.
  838. *
  839. * @return an identity-based set view of the keys contained in this map.
  840. * @see Object#equals(Object)
  841. * @see System#identityHashCode(Object)
  842. */
  843. public Set<K> keySet() {
  844. Set<K> ks = keySet;
  845. if (ks != null)
  846. return ks;
  847. else
  848. return keySet = new KeySet();
  849. }
  850. private class KeySet extends AbstractSet<K> {
  851. public Iterator<K> iterator() {
  852. return new KeyIterator();
  853. }
  854. public int size() {
  855. return size;
  856. }
  857. public boolean contains(Object o) {
  858. return containsKey(o);
  859. }
  860. public boolean remove(Object o) {
  861. int oldSize = size;
  862. IdentityHashMap.this.remove(o);
  863. return size != oldSize;
  864. }
  865. /*
  866. * Must revert from AbstractSet's impl to AbstractCollection's, as
  867. * the former contains an optimization that results in incorrect
  868. * behavior when c is a smaller "normal" (non-identity-based) Set.
  869. */
  870. public boolean removeAll(Collection<?> c) {
  871. boolean modified = false;
  872. for (Iterator i = iterator(); i.hasNext(); ) {
  873. if (c.contains(i.next())) {
  874. i.remove();
  875. modified = true;
  876. }
  877. }
  878. return modified;
  879. }
  880. public void clear() {
  881. IdentityHashMap.this.clear();
  882. }
  883. public int hashCode() {
  884. int result = 0;
  885. for (K key : this)
  886. result += System.identityHashCode(key);
  887. return result;
  888. }
  889. }
  890. /**
  891. * <p>Returns a collection view of the values contained in this map. The
  892. * collection is backed by the map, so changes to the map are reflected in
  893. * the collection, and vice-versa. If the map is modified while an
  894. * iteration over the collection is in progress, the results of the
  895. * iteration are undefined. The collection supports element removal,
  896. * which removes the corresponding mapping from the map, via the
  897. * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  898. * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> methods.
  899. * It does not support the <tt>add</tt> or <tt>addAll</tt> methods.
  900. *
  901. * <p><b>While the object returned by this method implements the
  902. * <tt>Collection</tt> interface, it does <i>not</i> obey
  903. * <tt>Collection's</tt> general contract. Like its backing map,
  904. * the collection returned by this method defines element equality as
  905. * reference-equality rather than object-equality. This affects the
  906. * behavior of its <tt>contains</tt>, <tt>remove</tt> and
  907. * <tt>containsAll</tt> methods.</b>
  908. *
  909. * @return a collection view of the values contained in this map.
  910. */
  911. public Collection<V> values() {
  912. Collection<V> vs = values;
  913. if (vs != null)
  914. return vs;
  915. else
  916. return values = new Values();
  917. }
  918. private class Values extends AbstractCollection<V> {
  919. public Iterator<V> iterator() {
  920. return new ValueIterator();
  921. }
  922. public int size() {
  923. return size;
  924. }
  925. public boolean contains(Object o) {
  926. return containsValue(o);
  927. }
  928. public boolean remove(Object o) {
  929. for (Iterator i = iterator(); i.hasNext(); ) {
  930. if (i.next() == o) {
  931. i.remove();
  932. return true;
  933. }
  934. }
  935. return false;
  936. }
  937. public void clear() {
  938. IdentityHashMap.this.clear();
  939. }
  940. }
  941. /**
  942. * Returns a set view of the mappings contained in this map. Each element
  943. * in the returned set is a reference-equality-based <tt>Map.Entry</tt>.
  944. * The set is backed by the map, so changes to the map are reflected in
  945. * the set, and vice-versa. If the map is modified while an iteration
  946. * over the set is in progress, the results of the iteration are
  947. * undefined. The set supports element removal, which removes the
  948. * corresponding mapping from the map, via the <tt>Iterator.remove</tt>,
  949. * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
  950. * <tt>clear</tt> methods. It does not support the <tt>add</tt> or
  951. * <tt>addAll</tt> methods.
  952. *
  953. * <p>Like the backing map, the <tt>Map.Entry</tt> objects in the set
  954. * returned by this method define key and value equality as
  955. * reference-equality rather than object-equality. This affects the
  956. * behavior of the <tt>equals</tt> and <tt>hashCode</tt> methods of these
  957. * <tt>Map.Entry</tt> objects. A reference-equality based <tt>Map.Entry
  958. * e</tt> is equal to an object <tt>o</tt> if and only if <tt>o</tt> is a
  959. * <tt>Map.Entry</tt> and <tt>e.getKey()==o.getKey() &&
  960. * e.getValue()==o.getValue()</tt>. To accommodate these equals
  961. * semantics, the <tt>hashCode</tt> method returns
  962. * <tt>System.identityHashCode(e.getKey()) ^
  963. * System.identityHashCode(e.getValue())</tt>.
  964. *
  965. * <p><b>Owing to the reference-equality-based semantics of the
  966. * <tt>Map.Entry</tt> instances in the set returned by this method,
  967. * it is possible that the symmetry and transitivity requirements of
  968. * the {@link Object#equals(Object)} contract may be violated if any of
  969. * the entries in the set is compared to a normal map entry, or if
  970. * the set returned by this method is compared to a set of normal map
  971. * entries (such as would be returned by a call to this method on a normal
  972. * map). However, the <tt>Object.equals</tt> contract is guaranteed to
  973. * hold among identity-based map entries, and among sets of such entries.
  974. * </b>
  975. *
  976. * @return a set view of the identity-mappings contained in this map.
  977. */
  978. public Set<Map.Entry<K,V>> entrySet() {
  979. Set<Map.Entry<K,V>> es = entrySet;
  980. if (es != null)
  981. return es;
  982. else
  983. return entrySet = new EntrySet();
  984. }
  985. private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
  986. public Iterator<Map.Entry<K,V>> iterator() {
  987. return new EntryIterator();
  988. }
  989. public boolean contains(Object o) {
  990. if (!(o instanceof Map.Entry))
  991. return false;
  992. Map.Entry entry = (Map.Entry)o;
  993. return containsMapping(entry.getKey(), entry.getValue());
  994. }
  995. public boolean remove(Object o) {
  996. if (!(o instanceof Map.Entry))
  997. return false;
  998. Map.Entry entry = (Map.Entry)o;
  999. return removeMapping(entry.getKey(), entry.getValue());
  1000. }
  1001. public int size() {
  1002. return size;
  1003. }
  1004. public void clear() {
  1005. IdentityHashMap.this.clear();
  1006. }
  1007. /*
  1008. * Must revert from AbstractSet's impl to AbstractCollection's, as
  1009. * the former contains an optimization that results in incorrect
  1010. * behavior when c is a smaller "normal" (non-identity-based) Set.
  1011. */
  1012. public boolean removeAll(Collection<?> c) {
  1013. boolean modified = false;
  1014. for (Iterator i = iterator(); i.hasNext(); ) {
  1015. if(c.contains(i.next())) {
  1016. i.remove();
  1017. modified = true;
  1018. }
  1019. }
  1020. return modified;
  1021. }
  1022. public Object[] toArray() {
  1023. List<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
  1024. for (Map.Entry<K,V> e : this)
  1025. c.add(new AbstractMap.SimpleEntry<K,V>(e));
  1026. return c.toArray();
  1027. }
  1028. public <T> T[] toArray(T[] a) {
  1029. return (T[])toArray(); // !!!!
  1030. }
  1031. }
  1032. private static final long serialVersionUID = 8188218128353913216L;
  1033. /**
  1034. * Save the state of the <tt>IdentityHashMap</tt> instance to a stream
  1035. * (i.e., serialize it).
  1036. *
  1037. * @serialData The <i>size</i> of the HashMap (the number of key-value
  1038. * mappings) (<tt>int</tt>), followed by the key (Object) and
  1039. * value (Object) for each key-value mapping represented by the
  1040. * IdentityHashMap. The key-value mappings are emitted in no
  1041. * particular order.
  1042. */
  1043. private void writeObject(java.io.ObjectOutputStream s)
  1044. throws java.io.IOException {
  1045. // Write out and any hidden stuff
  1046. s.defaultWriteObject();
  1047. // Write out size (number of Mappings)
  1048. s.writeInt(size);
  1049. // Write out keys and values (alternating)
  1050. Object[] tab = table;
  1051. for (int i = 0; i < tab.length; i += 2) {
  1052. Object key = tab[i];
  1053. if (key != null) {
  1054. s.writeObject(unmaskNull(key));
  1055. s.writeObject(tab[i + 1]);
  1056. }
  1057. }
  1058. }
  1059. /**
  1060. * Reconstitute the <tt>IdentityHashMap</tt> instance from a stream (i.e.,
  1061. * deserialize it).
  1062. */
  1063. private void readObject(java.io.ObjectInputStream s)
  1064. throws java.io.IOException, ClassNotFoundException {
  1065. // Read in any hidden stuff
  1066. s.defaultReadObject();
  1067. // Read in size (number of Mappings)
  1068. int size = s.readInt();
  1069. // Allow for 33% growth (i.e., capacity is >= 2* size()).
  1070. init(capacity((size*4)/3));
  1071. // Read the keys and values, and put the mappings in the table
  1072. for (int i=0; i<size; i++) {
  1073. K key = (K) s.readObject();
  1074. V value = (V) s.readObject();
  1075. putForCreate(key, value);
  1076. }
  1077. }
  1078. /**
  1079. * The put method for readObject. It does not resize the table,
  1080. * update modcount, etc.
  1081. */
  1082. private void putForCreate(K key, V value)
  1083. throws IOException
  1084. {
  1085. K k = (K)maskNull(key);
  1086. Object[] tab = table;
  1087. int len = tab.length;
  1088. int i = hash(k, len);
  1089. Object item;
  1090. while ( (item = tab[i]) != null) {
  1091. if (item == k)
  1092. throw new java.io.StreamCorruptedException();
  1093. i = nextKeyIndex(i, len);
  1094. }
  1095. tab[i] = k;
  1096. tab[i + 1] = value;
  1097. }
  1098. }