1. /*
  2. * @(#)IdentityHashMap.java 1.12 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. /**
  9. * This class implements the <tt>Map</tt> interface with a hash table, using
  10. * reference-equality in place of object-equality when comparing keys (and
  11. * values). In other words, in an <tt>IdentityHashMap</tt>, two keys
  12. * <tt>k1</tt> and <tt>k2</tt> are considered equal if and only if
  13. * <tt>(k1==k2)</tt>. (In normal <tt>Map</tt> implementations (like
  14. * <tt>HashMap</tt>) two keys <tt>k1</tt> and <tt>k2</tt> are considered equal
  15. * if and only if <tt>(k1==null ? k2==null : k1.equals(k2))</tt>.)
  16. *
  17. * <p><b>This class is <i>not</i> a general-purpose <tt>Map</tt>
  18. * implementation! While this class implements the <tt>Map</tt> interface, it
  19. * intentionally violates <tt>Map's</tt> general contract, which mandates the
  20. * use of the <tt>equals</tt> method when comparing objects. This class is
  21. * designed for use only in the rare cases wherein reference-equality
  22. * semantics are required.</b>
  23. *
  24. * <p>A typical use of this class is <i>topology-preserving object graph
  25. * transformations</i>, such as serialization or deep-copying. To perform such
  26. * a transformation, a program must maintain a "node table" that keeps track
  27. * of all the object references that have already been processed. The node
  28. * table must not equate distinct objects even if they happen to be equal.
  29. * Another typical use of this class is to maintain <i>proxy objects</i>. For
  30. * example, a debugging facility might wish to maintain a proxy object for
  31. * each object in the program being debugged.
  32. *
  33. * <p>This class provides all of the optional map operations, and permits
  34. * <tt>null</tt> values and the <tt>null</tt> key. This class makes no
  35. * guarantees as to the order of the map; in particular, it does not guarantee
  36. * that the order will remain constant over time.
  37. *
  38. * <p>This class provides constant-time performance for the basic
  39. * operations (<tt>get</tt> and <tt>put</tt>), assuming the system
  40. * identity hash function ({@link System#identityHashCode(Object)})
  41. * disperses elements properly among the buckets.
  42. *
  43. * <p>This class has one tuning parameter (which affects performance but not
  44. * semantics): <i>expected maximum size</i>. This parameter is the maximum
  45. * number of key-value mappings that the map is expected to hold. Internally,
  46. * this parameter is used to determine the number of buckets initially
  47. * comprising the hash table. The precise relationship between the expected
  48. * maximum size and the number of buckets is unspecified.
  49. *
  50. * <p>If the size of the map (the number of key-value mappings) sufficiently
  51. * exceeds the expected maximum size, the number of buckets is increased
  52. * Increasing the number of buckets ("rehashing") may be fairly expensive, so
  53. * it pays to create identity hash maps with a sufficiently large expected
  54. * maximum size. On the other hand, iteration over collection views requires
  55. * time proportional to the the number of buckets in the hash table, so it
  56. * pays not to set the expected maximum size too high if you are especially
  57. * concerned with iteration performance or memory usage.
  58. *
  59. * <p><b>Note that this implementation is not synchronized.</b> If multiple
  60. * threads access this map concurrently, and at least one of the threads
  61. * modifies the map structurally, it <i>must</i> be synchronized externally.
  62. * (A structural modification is any operation that adds or deletes one or
  63. * more mappings; merely changing the value associated with a key that an
  64. * instance already contains is not a structural modification.) This is
  65. * typically accomplished by synchronizing on some object that naturally
  66. * encapsulates the map. If no such object exists, the map should be
  67. * "wrapped" using the <tt>Collections.synchronizedMap</tt> method. This is
  68. * best done at creation time, to prevent accidental unsynchronized access to
  69. * the map: <pre>
  70. * Map m = Collections.synchronizedMap(new HashMap(...));
  71. * </pre>
  72. *
  73. * <p>The iterators returned by all of this class's "collection view methods"
  74. * are <i>fail-fast</i>: if the map is structurally modified at any time after
  75. * the iterator is created, in any way except through the iterator's own
  76. * <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
  77. * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
  78. * modification, the iterator fails quickly and cleanly, rather than risking
  79. * arbitrary, non-deterministic behavior at an undetermined time in the
  80. * future.
  81. *
  82. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  83. * as it is, generally speaking, impossible to make any hard guarantees in the
  84. * presence of unsynchronized concurrent modification. Fail-fast iterators
  85. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  86. * Therefore, it would be wrong to write a program that depended on this
  87. * exception for its correctness: <i>fail-fast iterators should be used only
  88. * to detect bugs.</i>
  89. *
  90. * <p>Implementation note: This is a simple <i>linear-probe</i> hash table,
  91. * as described for example in texts by Sedgewick and Knuth. The array
  92. * alternates holding keys and values. (This has better locality for large
  93. * tables than does using separate arrays.) For many JRE implementations
  94. * and operation mixes, this class will yield better performance than
  95. * {@link HashMap} (which uses <i>chaining</i> rather than linear-probing).
  96. *
  97. * <p>This class is a member of the
  98. * <a href="{@docRoot}/../guide/collections/index.html">
  99. * Java Collections Framework</a>.
  100. *
  101. * @see System#identityHashCode(Object)
  102. * @see Object#hashCode()
  103. * @see Collection
  104. * @see Map
  105. * @see HashMap
  106. * @see TreeMap
  107. * @author Doug Lea and Josh Bloch
  108. * @since 1.4
  109. */
  110. public class IdentityHashMap extends AbstractMap implements Map,
  111. java.io.Serializable, Cloneable
  112. {
  113. /**
  114. * The initial capacity used by the no-args constructor.
  115. * MUST be a power of two. The value 32 corresponds to the
  116. * (specified) expected maximum size of 21, given a load factor
  117. * of 2/3.
  118. */
  119. private static final int DEFAULT_CAPACITY = 32;
  120. /**
  121. * The minimum capacity, used if a lower value is implicitly specified
  122. * by either of the constructors with arguments. The value 4 corresponds
  123. * to an expected maximum size of 2, given a load factor of 2/3.
  124. * MUST be a power of two.
  125. */
  126. private static final int MINIMUM_CAPACITY = 4;
  127. /**
  128. * The maximum capacity, used if a higher value is implicitly specified
  129. * by either of the constructors with arguments.
  130. * MUST be a power of two <= 1<<29.
  131. */
  132. private static final int MAXIMUM_CAPACITY = 1 << 29;
  133. /**
  134. * The table, resized as necessary. Length MUST always be a power of two.
  135. */
  136. private transient Object[] table;
  137. /**
  138. * The number of key-value mappings contained in this identity hash map.
  139. *
  140. * @serial
  141. */
  142. private int size;
  143. /**
  144. * The number of modifications, to support fast-fail iterators
  145. */
  146. private transient volatile int modCount;
  147. /**
  148. * The next size value at which to resize (capacity * load factor).
  149. */
  150. private transient int threshold;
  151. /**
  152. * Value representing null keys inside tables.
  153. */
  154. private static final Object NULL_KEY = new Object();
  155. /**
  156. * Use NULL_KEY for key if it is null.
  157. */
  158. private static Object maskNull(Object key) {
  159. return (key == null ? NULL_KEY : key);
  160. }
  161. /**
  162. * Return internal representation of null key back to caller as null
  163. */
  164. private static Object unmaskNull(Object key) {
  165. return (key == NULL_KEY ? null : key);
  166. }
  167. /**
  168. * Constructs a new, empty identity hash map with a default expected
  169. * maximum size (21).
  170. */
  171. public IdentityHashMap() {
  172. init(DEFAULT_CAPACITY);
  173. }
  174. /**
  175. * Constructs a new, empty map with the specified expected maximum size.
  176. * Putting more than the expected number of key-value mappings into
  177. * the map may cause the internal data structure to grow, which may be
  178. * somewhat time-consuming.
  179. *
  180. * @param expectedMaxSize the expected maximum size of the map.
  181. * @throws IllegalArgumentException if <tt>expectedMaxSize</tt> is negative
  182. */
  183. public IdentityHashMap(int expectedMaxSize) {
  184. if (expectedMaxSize < 0)
  185. throw new IllegalArgumentException("expectedMaxSize is negative: "
  186. + expectedMaxSize);
  187. init(capacity(expectedMaxSize));
  188. }
  189. /**
  190. * Returns the appropriate capacity for the specified expected maximum
  191. * size. Returns the smallest power of two between MINIMUM_CAPACITY
  192. * and MAXIMUM_CAPACITY, inclusive, that is greater than
  193. * (3 * expectedMaxSize)/2, if such a number exists. Otherwise
  194. * returns MAXIMUM_CAPACITY. If (3 * expectedMaxSize)/2 is negative, it
  195. * is assumed that overflow has occurred, and MAXIMUM_CAPACITY is returned.
  196. */
  197. private int capacity(int expectedMaxSize) {
  198. // Compute min capacity for expectedMaxSize given a load factor of 2/3
  199. int minCapacity = (3 * expectedMaxSize)/2;
  200. // Compute the appropriate capacity
  201. int result;
  202. if (minCapacity > MAXIMUM_CAPACITY || minCapacity < 0) {
  203. result = MAXIMUM_CAPACITY;
  204. } else {
  205. result = MINIMUM_CAPACITY;
  206. while (result < minCapacity)
  207. result <<= 1;
  208. }
  209. return result;
  210. }
  211. /**
  212. * Initialize object to be an empty map with the specified initial
  213. * capacity, which is assumed to be a power of two between
  214. * MINIMUM_CAPACITY and MAXIMUM_CAPACITY inclusive.
  215. */
  216. private void init(int initCapacity) {
  217. // assert (initCapacity & -initCapacity) == initCapacity; // power of 2
  218. // assert initCapacity >= MINIMUM_CAPACITY;
  219. // assert initCapacity <= MAXIMUM_CAPACITY;
  220. threshold = (initCapacity * 2)/3;
  221. table = new Object[2 * initCapacity];
  222. }
  223. /**
  224. * Constructs a new identity hash map containing the keys-value mappings
  225. * in the specified map.
  226. *
  227. * @param m the map whose mappings are to be placed into this map.
  228. * @throws NullPointerException if the specified map is null.
  229. */
  230. public IdentityHashMap(Map m) {
  231. // Allow for a bit of growth
  232. this((int) ((1 + m.size()) * 1.1));
  233. putAll(m);
  234. }
  235. /**
  236. * Returns the number of key-value mappings in this identity hash map.
  237. *
  238. * @return the number of key-value mappings in this map.
  239. */
  240. public int size() {
  241. return size;
  242. }
  243. /**
  244. * Returns <tt>true</tt> if this identity hash map contains no key-value
  245. * mappings.
  246. *
  247. * @return <tt>true</tt> if this identity hash map contains no key-value
  248. * mappings.
  249. */
  250. public boolean isEmpty() {
  251. return size == 0;
  252. }
  253. /**
  254. * Return index for Object x.
  255. */
  256. private static int hash(Object x, int length) {
  257. int h = System.identityHashCode(x);
  258. // Multiply by -127, and left-shift to use least bit as part of hash
  259. return ((h << 1) - (h << 8)) & (length - 1);
  260. }
  261. /**
  262. * Circularly traverse table of size len.
  263. **/
  264. private static int nextKeyIndex(int i, int len) {
  265. return (i + 2 < len ? i + 2 : 0);
  266. }
  267. /**
  268. * Returns the value to which the specified key is mapped in this identity
  269. * hash map, or <tt>null</tt> if the map contains no mapping for
  270. * this key. A return value of <tt>null</tt> does not <i>necessarily</i>
  271. * indicate that the map contains no mapping for the key; it is also
  272. * possible that the map explicitly maps the key to <tt>null</tt>. The
  273. * <tt>containsKey</tt> method may be used to distinguish these two
  274. * cases.
  275. *
  276. * @param key the key whose associated value is to be returned.
  277. * @return the value to which this map maps the specified key, or
  278. * <tt>null</tt> if the map contains no mapping for this key.
  279. * @see #put(Object, Object)
  280. */
  281. public Object get(Object key) {
  282. Object k = maskNull(key);
  283. Object[] tab = table;
  284. int len = tab.length;
  285. int i = hash(k, len);
  286. while (true) {
  287. Object item = tab[i];
  288. if (item == k)
  289. return tab[i + 1];
  290. if (item == null)
  291. return item;
  292. i = nextKeyIndex(i, len);
  293. }
  294. }
  295. /**
  296. * Tests whether the specified object reference is a key in this identity
  297. * hash map.
  298. *
  299. * @param key possible key.
  300. * @return <code>true</code> if the specified object reference is a key
  301. * in this map.
  302. * @see #containsValue(Object)
  303. */
  304. public boolean containsKey(Object key) {
  305. Object k = maskNull(key);
  306. Object[] tab = table;
  307. int len = tab.length;
  308. int i = hash(k, len);
  309. while (true) {
  310. Object item = tab[i];
  311. if (item == k)
  312. return true;
  313. if (item == null)
  314. return false;
  315. i = nextKeyIndex(i, len);
  316. }
  317. }
  318. /**
  319. * Tests whether the specified object reference is a value in this identity
  320. * hash map.
  321. *
  322. * @param value value whose presence in this map is to be tested.
  323. * @return <tt>true</tt> if this map maps one or more keys to the
  324. * specified object reference.
  325. * @see #containsKey(Object)
  326. */
  327. public boolean containsValue(Object value) {
  328. Object[] tab = table;
  329. for (int i = 1; i < tab.length; i+= 2)
  330. if (tab[i] == value)
  331. return true;
  332. return false;
  333. }
  334. /**
  335. * Tests if the specified key-value mapping is in the map.
  336. *
  337. * @param key possible key.
  338. * @param value possible value.
  339. * @return <code>true</code> if and only if the specified key-value
  340. * mapping is in map.
  341. */
  342. private boolean containsMapping(Object key, Object value) {
  343. Object k = maskNull(key);
  344. Object[] tab = table;
  345. int len = tab.length;
  346. int i = hash(k, len);
  347. while (true) {
  348. Object item = tab[i];
  349. if (item == k)
  350. return tab[i + 1] == value;
  351. if (item == null)
  352. return false;
  353. i = nextKeyIndex(i, len);
  354. }
  355. }
  356. /**
  357. * Associates the specified value with the specified key in this identity
  358. * hash map. If the map previously contained a mapping for this key, the
  359. * old value is replaced.
  360. *
  361. * @param key the key with which the specified value is to be associated.
  362. * @param value the value to be associated with the specified key.
  363. * @return the previous value associated with <tt>key</tt>, or
  364. * <tt>null</tt> if there was no mapping for <tt>key</tt>. (A
  365. * <tt>null</tt> return can also indicate that the map previously
  366. * associated <tt>null</tt> with the specified key.)
  367. * @see Object#equals(Object)
  368. * @see #get(Object)
  369. * @see #containsKey(Object)
  370. */
  371. public Object put(Object key, Object value) {
  372. Object k = maskNull(key);
  373. Object[] tab = table;
  374. int len = tab.length;
  375. int i = hash(k, len);
  376. Object item;
  377. while ( (item = tab[i]) != null) {
  378. if (item == k) {
  379. Object oldValue = tab[i + 1];
  380. tab[i + 1] = value;
  381. return oldValue;
  382. }
  383. i = nextKeyIndex(i, len);
  384. }
  385. modCount++;
  386. tab[i] = k;
  387. tab[i + 1] = value;
  388. if (++size >= threshold)
  389. resize(len); // len == 2 * current capacity.
  390. return null;
  391. }
  392. /**
  393. * Resize the table to hold given capacity.
  394. *
  395. * @param newCapacity the new capacity, must be a power of two.
  396. */
  397. private void resize(int newCapacity) {
  398. // assert (newCapacity & -newCapacity) == newCapacity; // power of 2
  399. int newLength = newCapacity * 2;
  400. Object[] oldTable = table;
  401. int oldLength = oldTable.length;
  402. if (oldLength == 2*MAXIMUM_CAPACITY) { // can't expand any further
  403. if (threshold == MAXIMUM_CAPACITY-1)
  404. throw new IllegalStateException("Capacity exhausted.");
  405. threshold = MAXIMUM_CAPACITY-1; // Gigantic map!
  406. return;
  407. }
  408. if (oldLength >= newLength)
  409. return;
  410. Object[] newTable = new Object[newLength];
  411. threshold = newLength / 3;
  412. for (int j = 0; j < oldLength; j += 2) {
  413. Object key = oldTable[j];
  414. if (key != null) {
  415. Object value = oldTable[j+1];
  416. oldTable[j] = null;
  417. oldTable[j+1] = null;
  418. int i = hash(key, newLength);
  419. while (newTable[i] != null)
  420. i = nextKeyIndex(i, newLength);
  421. newTable[i] = key;
  422. newTable[i + 1] = value;
  423. }
  424. }
  425. table = newTable;
  426. }
  427. /**
  428. * Copies all of the mappings from the specified map to this map
  429. * These mappings will replace any mappings that
  430. * this map had for any of the keys currently in the specified map.<p>
  431. *
  432. * @param t mappings to be stored in this map.
  433. * @throws NullPointerException if the specified map is null.
  434. */
  435. public void putAll(Map t) {
  436. int n = t.size();
  437. if (n == 0)
  438. return;
  439. if (n > threshold) // conservatively pre-expand
  440. resize(capacity(n));
  441. for (Iterator it = t.entrySet().iterator(); it.hasNext(); ) {
  442. Entry e = (Entry) it.next();
  443. put(e.getKey(), e.getValue());
  444. }
  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 Object 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. Object oldValue = 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 t = (IdentityHashMap)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 implements Iterator {
  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 unecessary 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. Object key = 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 {
  733. public Object next() {
  734. return unmaskNull(traversalTable[nextIndex()]);
  735. }
  736. }
  737. private class ValueIterator extends IdentityHashMapIterator {
  738. public Object next() {
  739. return 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 extends IdentityHashMapIterator
  747. implements Map.Entry
  748. {
  749. public Object next() {
  750. nextIndex();
  751. return this;
  752. }
  753. public Object getKey() {
  754. // Provide a better exception than out of bounds index
  755. if (lastReturnedIndex < 0)
  756. throw new IllegalStateException("Entry was removed");
  757. return unmaskNull(traversalTable[lastReturnedIndex]);
  758. }
  759. public Object getValue() {
  760. // Provide a better exception than out of bounds index
  761. if (lastReturnedIndex < 0)
  762. throw new IllegalStateException("Entry was removed");
  763. return traversalTable[lastReturnedIndex+1];
  764. }
  765. public Object setValue(Object value) {
  766. // It would be mean-spirited to proceed here if remove() called
  767. if (lastReturnedIndex < 0)
  768. throw new IllegalStateException("Entry was removed");
  769. Object oldValue = traversalTable[lastReturnedIndex+1];
  770. traversalTable[lastReturnedIndex+1] = value;
  771. // if shadowing, force into main table
  772. if (traversalTable != IdentityHashMap.this.table)
  773. put(traversalTable[lastReturnedIndex], value);
  774. return oldValue;
  775. }
  776. public boolean equals(Object o) {
  777. if (!(o instanceof Map.Entry))
  778. return false;
  779. Map.Entry e = (Map.Entry)o;
  780. return e.getKey() == getKey() &&
  781. e.getValue() == getValue();
  782. }
  783. public int hashCode() {
  784. return System.identityHashCode(getKey()) ^
  785. System.identityHashCode(getValue());
  786. }
  787. public String toString() {
  788. return getKey() + "=" + getValue();
  789. }
  790. }
  791. // Views
  792. /**
  793. * This field is initialized to contain an instance of the entry set
  794. * view the first time this view is requested. The view is stateless,
  795. * so there's no reason to create more than one.
  796. */
  797. private transient Set entrySet = null;
  798. /**
  799. * Returns an identity-based set view of the keys contained in this map.
  800. * The set is backed by the map, so changes to the map are reflected in
  801. * the set, and vice-versa. If the map is modified while an iteration
  802. * over the set is in progress, the results of the iteration are
  803. * undefined. The set supports element removal, which removes the
  804. * corresponding mapping from the map, via the <tt>Iterator.remove</tt>,
  805. * <tt>Set.remove</tt>, <tt>removeAll</tt> <tt>retainAll</tt>, and
  806. * <tt>clear</tt> methods. It does not support the <tt>add</tt> or
  807. * <tt>addAll</tt> methods.
  808. *
  809. * <p><b>While the object returned by this method implements the
  810. * <tt>Set</tt> interface, it does <i>not</i> obey <tt>Set's</tt> general
  811. * contract. Like its backing map, the set returned by this method
  812. * defines element equality as reference-equality rather than
  813. * object-equality. This affects the behavior of its <tt>contains</tt>,
  814. * <tt>remove</tt>, <tt>containsAll</tt>, <tt>equals</tt>, and
  815. * <tt>hashCode</tt> methods.</b>
  816. *
  817. * <p>The <tt>equals</tt> method of the returned set returns <tt>true</tt>
  818. * only if the specified object is a set containing exactly the same
  819. * object references as the returned set. The symmetry and transitivity
  820. * requirements of the <tt>Object.equals</tt> contract may be violated if
  821. * the set returned by this method is compared to a normal set. However,
  822. * the <tt>Object.equals</tt> contract is guaranteed to hold among sets
  823. * returned by this method.</b>
  824. *
  825. * <p>The <tt>hashCode</tt> method of the returned set returns the sum of
  826. * the <i>identity hashcodes</i> of the elements in the set, rather than
  827. * the sum of their hashcodes. This is mandated by the change in the
  828. * semantics of the <tt>equals</tt> method, in order to enforce the
  829. * general contract of the <tt>Object.hashCode</tt> method among sets
  830. * returned by this method.
  831. *
  832. * @return an identity-based set view of the keys contained in this map.
  833. * @see Object#equals(Object)
  834. * @see System#identityHashCode(Object)
  835. */
  836. public Set keySet() {
  837. Set ks = keySet;
  838. if (ks != null)
  839. return ks;
  840. else
  841. return keySet = new KeySet();
  842. }
  843. private class KeySet extends AbstractSet {
  844. public Iterator iterator() {
  845. return new KeyIterator();
  846. }
  847. public int size() {
  848. return size;
  849. }
  850. public boolean contains(Object o) {
  851. return containsKey(o);
  852. }
  853. public boolean remove(Object o) {
  854. int oldSize = size;
  855. IdentityHashMap.this.remove(o);
  856. return size != oldSize;
  857. }
  858. /*
  859. * Must revert from AbstractSet's impl to AbstractCollection's, as
  860. * the former contains an optimization that results in incorrect
  861. * behavior when c is a smaller "normal" (non-identity-based) Set.
  862. */
  863. public boolean removeAll(Collection c) {
  864. boolean modified = false;
  865. for (Iterator i = iterator(); i.hasNext(); ) {
  866. if(c.contains(i.next())) {
  867. i.remove();
  868. modified = true;
  869. }
  870. }
  871. return modified;
  872. }
  873. public void clear() {
  874. IdentityHashMap.this.clear();
  875. }
  876. public int hashCode() {
  877. int result = 0;
  878. for (Iterator i = iterator(); i.hasNext(); )
  879. result += System.identityHashCode(i.next());
  880. return result;
  881. }
  882. }
  883. /**
  884. * <p>Returns a collection view of the values contained in this map. The
  885. * collection is backed by the map, so changes to the map are reflected in
  886. * the collection, and vice-versa. If the map is modified while an
  887. * iteration over the collection is in progress, the results of the
  888. * iteration are undefined. The collection supports element removal,
  889. * which removes the corresponding mapping from the map, via the
  890. * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  891. * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> methods.
  892. * It does not support the <tt>add</tt> or <tt>addAll</tt> methods.
  893. *
  894. * <p><b>While the object returned by this method implements the
  895. * <tt>Collection</tt> interface, it does <i>not</i> obey
  896. * <tt>Collection's</tt> general contract. Like its backing map,
  897. * the collection returned by this method defines element equality as
  898. * reference-equality rather than object-equality. This affects the
  899. * behavior of its <tt>contains</tt>, <tt>remove</tt> and
  900. * <tt>containsAll</tt> methods.</b>
  901. *
  902. * @return a collection view of the values contained in this map.
  903. */
  904. public Collection values() {
  905. Collection vs = values;
  906. if (vs != null)
  907. return vs;
  908. else
  909. return values = new Values();
  910. }
  911. private class Values extends AbstractCollection {
  912. public Iterator iterator() {
  913. return new ValueIterator();
  914. }
  915. public int size() {
  916. return size;
  917. }
  918. public boolean contains(Object o) {
  919. return containsValue(o);
  920. }
  921. public boolean remove(Object o) {
  922. for (Iterator i = iterator(); i.hasNext(); ) {
  923. if (i.next() == o) {
  924. i.remove();
  925. return true;
  926. }
  927. }
  928. return false;
  929. }
  930. public void clear() {
  931. IdentityHashMap.this.clear();
  932. }
  933. }
  934. /**
  935. * Returns a set view of the mappings contained in this map. Each element
  936. * in the returned set is a reference-equality-based <tt>Map.Entry</tt>.
  937. * The set is backed by the map, so changes to the map are reflected in
  938. * the set, and vice-versa. If the map is modified while an iteration
  939. * over the set is in progress, the results of the iteration are
  940. * undefined. The set supports element removal, which removes the
  941. * corresponding mapping from the map, via the <tt>Iterator.remove</tt>,
  942. * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
  943. * <tt>clear</tt> methods. It does not support the <tt>add</tt> or
  944. * <tt>addAll</tt> methods.
  945. *
  946. * <p>Like the backing map, the <tt>Map.Entry</tt> objects in the set
  947. * returned by this method define key and value equality as
  948. * reference-equality rather than object-equality. This affects the
  949. * behavior of the <tt>equals</tt> and <tt>hashCode</tt> methods of these
  950. * <tt>Map.Entry</tt> objects. A reference-equality based <tt>Map.Entry
  951. * e</tt> is equal to an object <tt>o</tt> if and only if <tt>o</tt> is a
  952. * <tt>Map.Entry</tt> and <tt>e.getKey()==o.getKey() &&
  953. * e.getValue()==o.getValue()</tt>. To accommodate these equals
  954. * semantics, the <tt>hashCode</tt> method returns
  955. * <tt>System.identityHashCode(e.getKey()) ^
  956. * System.identityHashCode(e.getValue())</tt>.
  957. *
  958. * <p><b>Owing to the reference-equality-based semantics of the
  959. * <tt>Map.Entry</tt> instances in the set returned by this method,
  960. * it is possible that the symmetry and transitivity requirements of
  961. * the {@link Object#equals(Object)} contract may be violated if any of
  962. * the entries in the set is compared to a normal map entry, or if
  963. * the set returned by this method is compared to a set of normal map
  964. * entries (such as would be returned by a call to this method on a normal
  965. * map). However, the <tt>Object.equals</tt> contract is guaranteed to
  966. * hold among identity-based map entries, and among sets of such entries.
  967. * </b>
  968. *
  969. * @return a set view of the identity-mappings contained in this map.
  970. */
  971. public Set entrySet() {
  972. Set es = entrySet;
  973. if (es != null)
  974. return es;
  975. else
  976. return entrySet = new EntrySet();
  977. }
  978. private class EntrySet extends AbstractSet {
  979. public Iterator iterator() {
  980. return new EntryIterator();
  981. }
  982. public boolean contains(Object o) {
  983. if (!(o instanceof Map.Entry))
  984. return false;
  985. Map.Entry entry = (Map.Entry)o;
  986. return containsMapping(entry.getKey(), entry.getValue());
  987. }
  988. public boolean remove(Object o) {
  989. if (!(o instanceof Map.Entry))
  990. return false;
  991. Map.Entry entry = (Map.Entry)o;
  992. return removeMapping(entry.getKey(), entry.getValue());
  993. }
  994. public int size() {
  995. return size;
  996. }
  997. public void clear() {
  998. IdentityHashMap.this.clear();
  999. }
  1000. /*
  1001. * Must revert from AbstractSet's impl to AbstractCollection's, as
  1002. * the former contains an optimization that results in incorrect
  1003. * behavior when c is a smaller "normal" (non-identity-based) Set.
  1004. */
  1005. public boolean removeAll(Collection c) {
  1006. boolean modified = false;
  1007. for (Iterator i = iterator(); i.hasNext(); ) {
  1008. if(c.contains(i.next())) {
  1009. i.remove();
  1010. modified = true;
  1011. }
  1012. }
  1013. return modified;
  1014. }
  1015. public Object[] toArray() {
  1016. Collection c = new ArrayList(size());
  1017. for (Iterator i = iterator(); i.hasNext(); )
  1018. c.add(new AbstractMap.SimpleEntry((Map.Entry) i.next()));
  1019. return c.toArray();
  1020. }
  1021. public Object[] toArray(Object a[]) {
  1022. Collection c = new ArrayList(size());
  1023. for (Iterator i = iterator(); i.hasNext(); )
  1024. c.add(new AbstractMap.SimpleEntry((Map.Entry) i.next()));
  1025. return c.toArray(a);
  1026. }
  1027. }
  1028. /**
  1029. * Save the state of the <tt>IdentityHashMap</tt> instance to a stream
  1030. * (i.e., serialize it).
  1031. *
  1032. * @serialData The <i>size</i> of the HashMap (the number of key-value
  1033. * mappings) (<tt>int</tt>), followed by the key (Object) and
  1034. * value (Object) for each key-value mapping represented by the
  1035. * IdentityHashMap. The key-value mappings are emitted in no
  1036. * particular order.
  1037. */
  1038. private void writeObject(java.io.ObjectOutputStream s)
  1039. throws java.io.IOException {
  1040. // Write out and any hidden stuff
  1041. s.defaultWriteObject();
  1042. // Write out size (number of Mappings)
  1043. s.writeInt(size);
  1044. // Write out keys and values (alternating)
  1045. Object[] tab = table;
  1046. for (int i = 0; i < tab.length; i += 2) {
  1047. Object key = tab[i];
  1048. if (key != null) {
  1049. s.writeObject(unmaskNull(key));
  1050. s.writeObject(tab[i + 1]);
  1051. }
  1052. }
  1053. }
  1054. /**
  1055. * Reconstitute the <tt>IdentityHashMap</tt> instance from a stream (i.e.,
  1056. * deserialize it).
  1057. */
  1058. private void readObject(java.io.ObjectInputStream s)
  1059. throws java.io.IOException, ClassNotFoundException {
  1060. // Read in any hidden stuff
  1061. s.defaultReadObject();
  1062. // Read in size (number of Mappings)
  1063. int size = s.readInt();
  1064. // Allow for 33% growth (i.e., capacity is >= 2* size()).
  1065. init(capacity((size*4)/3));
  1066. // Read the keys and values, and put the mappings in the table
  1067. for (int i=0; i<size; i++) {
  1068. Object key = s.readObject();
  1069. Object value = s.readObject();
  1070. put(key, value);
  1071. }
  1072. }
  1073. }