IdentityHashMap.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. /* IdentityHashMap.java -- a class providing a hashtable data structure,
  2. mapping Object --> Object, which uses object identity for hashing.
  3. Copyright (C) 2001, 2002 Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import java.io.*;
  34. /**
  35. * This class provides a hashtable-backed implementation of the
  36. * Map interface, but uses object identity to do its hashing. In fact,
  37. * it uses object identity for comparing values, as well. It uses a
  38. * linear-probe hash table, which may have faster performance
  39. * than the chaining employed by HashMap.
  40. * <p>
  41. *
  42. * <em>WARNING: This is not a general purpose map. Because it uses
  43. * System.identityHashCode and ==, instead of hashCode and equals, for
  44. * comparison, it violated Map's general contract, and may cause
  45. * undefined behavior when compared to other maps which are not
  46. * IdentityHashMaps. This is designed only for the rare cases when
  47. * identity semantics are needed.</em> An example use is
  48. * topology-preserving graph transformations, such as deep cloning,
  49. * or as proxy object mapping such as in debugging.
  50. * <p>
  51. *
  52. * This map permits <code>null</code> keys and values, and does not
  53. * guarantee that elements will stay in the same order over time. The
  54. * basic operations (<code>get</code> and <code>put</code>) take
  55. * constant time, provided System.identityHashCode is decent. You can
  56. * tune the behavior by specifying the expected maximum size. As more
  57. * elements are added, the map may need to allocate a larger table,
  58. * which can be expensive.
  59. * <p>
  60. *
  61. * This implementation is unsynchronized. If you want multi-thread
  62. * access to be consistent, you must synchronize it, perhaps by using
  63. * <code>Collections.synchronizedMap(new IdentityHashMap(...));</code>.
  64. * The iterators are <i>fail-fast</i>, meaning that a structural modification
  65. * made to the map outside of an iterator's remove method cause the
  66. * iterator, and in the case of the entrySet, the Map.Entry, to
  67. * fail with a {@link ConcurrentModificationException}.
  68. *
  69. * @author Tom Tromey <tromey@redhat.com>
  70. * @author Eric Blake <ebb9@email.byu.edu>
  71. * @see System#identityHashCode(Object)
  72. * @see Collection
  73. * @see Map
  74. * @see HashMap
  75. * @see TreeMap
  76. * @see LinkedHashMap
  77. * @see WeakHashMap
  78. * @since 1.4
  79. * @status updated to 1.4
  80. */
  81. public class IdentityHashMap extends AbstractMap
  82. implements Map, Serializable, Cloneable
  83. {
  84. /** The default capacity. */
  85. private static final int DEFAULT_CAPACITY = 21;
  86. /**
  87. * This object is used to mark deleted items. Package visible for use by
  88. * nested classes.
  89. */
  90. static final Object tombstone = new Object();
  91. /**
  92. * This object is used to mark empty slots. We need this because
  93. * using null is ambiguous. Package visible for use by nested classes.
  94. */
  95. static final Object emptyslot = new Object();
  96. /**
  97. * Compatible with JDK 1.4.
  98. */
  99. private static final long serialVersionUID = 8188218128353913216L;
  100. /**
  101. * The number of mappings in the table. Package visible for use by nested
  102. * classes.
  103. * @serial
  104. */
  105. int size;
  106. /**
  107. * The table itself. Package visible for use by nested classes.
  108. */
  109. transient Object[] table;
  110. /**
  111. * The number of structural modifications made so far. Package visible for
  112. * use by nested classes.
  113. */
  114. transient int modCount;
  115. /**
  116. * The cache for {@link #entrySet()}.
  117. */
  118. private transient Set entries;
  119. /**
  120. * The threshold for rehashing, which is 75% of (table.length / 2).
  121. */
  122. private transient int threshold;
  123. /**
  124. * Create a new IdentityHashMap with the default capacity (21 entries).
  125. */
  126. public IdentityHashMap()
  127. {
  128. this(DEFAULT_CAPACITY);
  129. }
  130. /**
  131. * Create a new IdentityHashMap with the indicated number of
  132. * entries. If the number of elements added to this hash map
  133. * exceeds this maximum, the map will grow itself; however, that
  134. * incurs a performance penalty.
  135. *
  136. * @param max initial size
  137. * @throws IllegalArgumentException if max is negative
  138. */
  139. public IdentityHashMap(int max)
  140. {
  141. if (max < 0)
  142. throw new IllegalArgumentException();
  143. // Need at least two slots, or hash() will break.
  144. if (max < 2)
  145. max = 2;
  146. table = new Object[max << 1];
  147. Arrays.fill(table, emptyslot);
  148. threshold = (max >> 2) * 3;
  149. }
  150. /**
  151. * Create a new IdentityHashMap whose contents are taken from the
  152. * given Map.
  153. *
  154. * @param m The map whose elements are to be put in this map
  155. * @throws NullPointerException if m is null
  156. */
  157. public IdentityHashMap(Map m)
  158. {
  159. this(Math.max(m.size() << 1, DEFAULT_CAPACITY));
  160. putAll(m);
  161. }
  162. /**
  163. * Remove all mappings from this map.
  164. */
  165. public void clear()
  166. {
  167. if (size != 0)
  168. {
  169. modCount++;
  170. Arrays.fill(table, emptyslot);
  171. size = 0;
  172. }
  173. }
  174. /**
  175. * Creates a shallow copy where keys and values are not cloned.
  176. */
  177. public Object clone()
  178. {
  179. try
  180. {
  181. IdentityHashMap copy = (IdentityHashMap) super.clone();
  182. copy.table = (Object[]) table.clone();
  183. copy.entries = null; // invalidate the cache
  184. return copy;
  185. }
  186. catch (CloneNotSupportedException e)
  187. {
  188. // Can't happen.
  189. return null;
  190. }
  191. }
  192. /**
  193. * Tests whether the specified key is in this map. Unlike normal Maps,
  194. * this test uses <code>entry == key</code> instead of
  195. * <code>entry == null ? key == null : entry.equals(key)</code>.
  196. *
  197. * @param key the key to look for
  198. * @return true if the key is contained in the map
  199. * @see #containsValue(Object)
  200. * @see #get(Object)
  201. */
  202. public boolean containsKey(Object key)
  203. {
  204. return key == table[hash(key)];
  205. }
  206. /**
  207. * Returns true if this HashMap contains the value. Unlike normal maps,
  208. * this test uses <code>entry == value</code> instead of
  209. * <code>entry == null ? value == null : entry.equals(value)</code>.
  210. *
  211. * @param value the value to search for in this HashMap
  212. * @return true if at least one key maps to the value
  213. * @see #containsKey(Object)
  214. */
  215. public boolean containsValue(Object value)
  216. {
  217. for (int i = table.length - 1; i > 0; i -= 2)
  218. if (table[i] == value)
  219. return true;
  220. return false;
  221. }
  222. /**
  223. * Returns a "set view" of this Map's entries. The set is backed by
  224. * the Map, so changes in one show up in the other. The set supports
  225. * element removal, but not element addition.
  226. * <p>
  227. *
  228. * <em>The semantics of this set, and of its contained entries, are
  229. * different from the contract of Set and Map.Entry in order to make
  230. * IdentityHashMap work. This means that while you can compare these
  231. * objects between IdentityHashMaps, comparing them with regular sets
  232. * or entries is likely to have undefined behavior.</em> The entries
  233. * in this set are reference-based, rather than the normal object
  234. * equality. Therefore, <code>e1.equals(e2)</code> returns
  235. * <code>e1.getKey() == e2.getKey() && e1.getValue() == e2.getValue()</code>,
  236. * and <code>e.hashCode()</code> returns
  237. * <code>System.identityHashCode(e.getKey()) ^
  238. * System.identityHashCode(e.getValue())</code>.
  239. * <p>
  240. *
  241. * Note that the iterators for all three views, from keySet(), entrySet(),
  242. * and values(), traverse the Map in the same sequence.
  243. *
  244. * @return a set view of the entries
  245. * @see #keySet()
  246. * @see #values()
  247. * @see Map.Entry
  248. */
  249. public Set entrySet()
  250. {
  251. if (entries == null)
  252. entries = new AbstractSet()
  253. {
  254. public int size()
  255. {
  256. return size;
  257. }
  258. public Iterator iterator()
  259. {
  260. return new IdentityIterator(ENTRIES);
  261. }
  262. public void clear()
  263. {
  264. IdentityHashMap.this.clear();
  265. }
  266. public boolean contains(Object o)
  267. {
  268. if (! (o instanceof Map.Entry))
  269. return false;
  270. Map.Entry m = (Map.Entry) o;
  271. return m.getValue() == table[hash(m.getKey()) + 1];
  272. }
  273. public int hashCode()
  274. {
  275. return IdentityHashMap.this.hashCode();
  276. }
  277. public boolean remove(Object o)
  278. {
  279. if (! (o instanceof Map.Entry))
  280. return false;
  281. Object key = ((Map.Entry) o).getKey();
  282. int h = hash(key);
  283. if (table[h] == key)
  284. {
  285. size--;
  286. modCount++;
  287. table[h] = tombstone;
  288. table[h + 1] = tombstone;
  289. return true;
  290. }
  291. return false;
  292. }
  293. };
  294. return entries;
  295. }
  296. /**
  297. * Compares two maps for equality. This returns true only if both maps
  298. * have the same reference-identity comparisons. While this returns
  299. * <code>this.entrySet().equals(m.entrySet())</code> as specified by Map,
  300. * this will not work with normal maps, since the entry set compares
  301. * with == instead of .equals.
  302. *
  303. * @param o the object to compare to
  304. * @return true if it is equal
  305. */
  306. public boolean equals(Object o)
  307. {
  308. // Why did Sun specify this one? The superclass does the right thing.
  309. return super.equals(o);
  310. }
  311. /**
  312. * Return the value in this Map associated with the supplied key, or
  313. * <code>null</code> if the key maps to nothing.
  314. *
  315. * <p>NOTE: Since the value could also be null, you must use
  316. * containsKey to see if this key actually maps to something.
  317. * Unlike normal maps, this tests for the key with <code>entry ==
  318. * key</code> instead of <code>entry == null ? key == null :
  319. * entry.equals(key)</code>.
  320. *
  321. * @param key the key for which to fetch an associated value
  322. * @return what the key maps to, if present
  323. * @see #put(Object, Object)
  324. * @see #containsKey(Object)
  325. */
  326. public Object get(Object key)
  327. {
  328. int h = hash(key);
  329. return table[h] == key ? table[h + 1] : null;
  330. }
  331. /**
  332. * Returns the hashcode of this map. This guarantees that two
  333. * IdentityHashMaps that compare with equals() will have the same hash code,
  334. * but may break with comparison to normal maps since it uses
  335. * System.identityHashCode() instead of hashCode().
  336. *
  337. * @return the hash code
  338. */
  339. public int hashCode()
  340. {
  341. int hash = 0;
  342. for (int i = table.length - 2; i >= 0; i -= 2)
  343. {
  344. Object key = table[i];
  345. if (key == emptyslot || key == tombstone)
  346. continue;
  347. hash += (System.identityHashCode(key)
  348. ^ System.identityHashCode(table[i + 1]));
  349. }
  350. return hash;
  351. }
  352. /**
  353. * Returns true if there are no key-value mappings currently in this Map
  354. * @return <code>size() == 0</code>
  355. */
  356. public boolean isEmpty()
  357. {
  358. return size == 0;
  359. }
  360. /**
  361. * Returns a "set view" of this Map's keys. The set is backed by the
  362. * Map, so changes in one show up in the other. The set supports
  363. * element removal, but not element addition.
  364. * <p>
  365. *
  366. * <em>The semantics of this set are different from the contract of Set
  367. * in order to make IdentityHashMap work. This means that while you can
  368. * compare these objects between IdentityHashMaps, comparing them with
  369. * regular sets is likely to have undefined behavior.</em> The hashCode
  370. * of the set is the sum of the identity hash codes, instead of the
  371. * regular hashCodes, and equality is determined by reference instead
  372. * of by the equals method.
  373. * <p>
  374. *
  375. * @return a set view of the keys
  376. * @see #values()
  377. * @see #entrySet()
  378. */
  379. public Set keySet()
  380. {
  381. if (keys == null)
  382. keys = new AbstractSet()
  383. {
  384. public int size()
  385. {
  386. return size;
  387. }
  388. public Iterator iterator()
  389. {
  390. return new IdentityIterator(KEYS);
  391. }
  392. public void clear()
  393. {
  394. IdentityHashMap.this.clear();
  395. }
  396. public boolean contains(Object o)
  397. {
  398. return containsKey(o);
  399. }
  400. public int hashCode()
  401. {
  402. int hash = 0;
  403. for (int i = table.length - 2; i >= 0; i -= 2)
  404. {
  405. Object key = table[i];
  406. if (key == emptyslot || key == tombstone)
  407. continue;
  408. hash += System.identityHashCode(key);
  409. }
  410. return hash;
  411. }
  412. public boolean remove(Object o)
  413. {
  414. int h = hash(o);
  415. if (table[h] == o)
  416. {
  417. size--;
  418. modCount++;
  419. table[h] = tombstone;
  420. table[h + 1] = tombstone;
  421. return true;
  422. }
  423. return false;
  424. }
  425. };
  426. return keys;
  427. }
  428. /**
  429. * Puts the supplied value into the Map, mapped by the supplied key.
  430. * The value may be retrieved by any object which <code>equals()</code>
  431. * this key. NOTE: Since the prior value could also be null, you must
  432. * first use containsKey if you want to see if you are replacing the
  433. * key's mapping. Unlike normal maps, this tests for the key
  434. * with <code>entry == key</code> instead of
  435. * <code>entry == null ? key == null : entry.equals(key)</code>.
  436. *
  437. * @param key the key used to locate the value
  438. * @param value the value to be stored in the HashMap
  439. * @return the prior mapping of the key, or null if there was none
  440. * @see #get(Object)
  441. */
  442. public Object put(Object key, Object value)
  443. {
  444. // Rehash if the load factor is too high.
  445. if (size > threshold)
  446. {
  447. Object[] old = table;
  448. // This isn't necessarily prime, but it is an odd number of key/value
  449. // slots, which has a higher probability of fewer collisions.
  450. table = new Object[old.length << 1 + 2];
  451. Arrays.fill(table, emptyslot);
  452. size = 0;
  453. threshold = (table.length >>> 3) * 3;
  454. for (int i = old.length - 2; i >= 0; i -= 2)
  455. {
  456. Object oldkey = old[i];
  457. if (oldkey != tombstone && oldkey != emptyslot)
  458. // Just use put. This isn't very efficient, but it is ok.
  459. put(oldkey, old[i + 1]);
  460. }
  461. }
  462. int h = hash(key);
  463. if (table[h] == key)
  464. {
  465. Object r = table[h + 1];
  466. table[h + 1] = value;
  467. return r;
  468. }
  469. // At this point, we add a new mapping.
  470. modCount++;
  471. size++;
  472. table[h] = key;
  473. table[h + 1] = value;
  474. return null;
  475. }
  476. /**
  477. * Copies all of the mappings from the specified map to this. If a key
  478. * is already in this map, its value is replaced.
  479. *
  480. * @param m the map to copy
  481. * @throws NullPointerException if m is null
  482. */
  483. public void putAll(Map m)
  484. {
  485. // Why did Sun specify this one? The superclass does the right thing.
  486. super.putAll(m);
  487. }
  488. /**
  489. * Removes from the HashMap and returns the value which is mapped by
  490. * the supplied key. If the key maps to nothing, then the HashMap
  491. * remains unchanged, and <code>null</code> is returned.
  492. *
  493. * NOTE: Since the value could also be null, you must use
  494. * containsKey to see if you are actually removing a mapping.
  495. * Unlike normal maps, this tests for the key with <code>entry ==
  496. * key</code> instead of <code>entry == null ? key == null :
  497. * entry.equals(key)</code>.
  498. *
  499. * @param key the key used to locate the value to remove
  500. * @return whatever the key mapped to, if present
  501. */
  502. public Object remove(Object key)
  503. {
  504. int h = hash(key);
  505. if (table[h] == key)
  506. {
  507. modCount++;
  508. size--;
  509. Object r = table[h + 1];
  510. table[h] = tombstone;
  511. table[h + 1] = tombstone;
  512. return r;
  513. }
  514. return null;
  515. }
  516. /**
  517. * Returns the number of kay-value mappings currently in this Map
  518. * @return the size
  519. */
  520. public int size()
  521. {
  522. return size;
  523. }
  524. /**
  525. * Returns a "collection view" (or "bag view") of this Map's values.
  526. * The collection is backed by the Map, so changes in one show up
  527. * in the other. The collection supports element removal, but not element
  528. * addition.
  529. * <p>
  530. *
  531. * <em>The semantics of this set are different from the contract of
  532. * Collection in order to make IdentityHashMap work. This means that
  533. * while you can compare these objects between IdentityHashMaps, comparing
  534. * them with regular sets is likely to have undefined behavior.</em>
  535. * Likewise, contains and remove go by == instead of equals().
  536. * <p>
  537. *
  538. * @return a bag view of the values
  539. * @see #keySet()
  540. * @see #entrySet()
  541. */
  542. public Collection values()
  543. {
  544. if (values == null)
  545. values = new AbstractCollection()
  546. {
  547. public int size()
  548. {
  549. return size;
  550. }
  551. public Iterator iterator()
  552. {
  553. return new IdentityIterator(VALUES);
  554. }
  555. public void clear()
  556. {
  557. IdentityHashMap.this.clear();
  558. }
  559. public boolean remove(Object o)
  560. {
  561. for (int i = table.length - 1; i > 0; i -= 2)
  562. if (table[i] == o)
  563. {
  564. modCount++;
  565. table[i - 1] = tombstone;
  566. table[i] = tombstone;
  567. size--;
  568. return true;
  569. }
  570. return false;
  571. }
  572. };
  573. return values;
  574. }
  575. /**
  576. * Helper method which computes the hash code, then traverses the table
  577. * until it finds the key, or the spot where the key would go.
  578. *
  579. * @param key the key to check
  580. * @return the index where the key belongs
  581. * @see #IdentityHashMap(int)
  582. * @see #put(Object, Object)
  583. */
  584. // Package visible for use by nested classes.
  585. int hash(Object key)
  586. {
  587. // Implementation note: it is feasible for the table to have no
  588. // emptyslots, if it is full with entries and tombstones, so we must
  589. // remember where we started. If we encounter the key or an emptyslot,
  590. // we are done. If we encounter a tombstone, the key may still be in
  591. // the array. If we don't encounter the key, we use the first emptyslot
  592. // or tombstone we encountered as the location where the key would go.
  593. // By requiring at least 2 key/value slots, and rehashing at 75%
  594. // capacity, we guarantee that there will always be either an emptyslot
  595. // or a tombstone somewhere in the table.
  596. int h = Math.abs(System.identityHashCode(key) % (table.length >> 1)) << 1;
  597. int del = -1;
  598. int save = h;
  599. do
  600. {
  601. if (table[h] == key)
  602. return h;
  603. if (table[h] == emptyslot)
  604. break;
  605. if (table[h] == tombstone && del < 0)
  606. del = h;
  607. h -= 2;
  608. if (h < 0)
  609. h = table.length - 2;
  610. }
  611. while (h != save);
  612. return del < 0 ? h : del;
  613. }
  614. /**
  615. * This class allows parameterized iteration over IdentityHashMaps. Based
  616. * on its construction, it returns the key or value of a mapping, or
  617. * creates the appropriate Map.Entry object with the correct fail-fast
  618. * semantics and identity comparisons.
  619. *
  620. * @author Tom Tromey <tromey@redhat.com>
  621. * @author Eric Blake <ebb9@email.byu.edu>
  622. */
  623. private final class IdentityIterator implements Iterator
  624. {
  625. /**
  626. * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
  627. * or {@link #ENTRIES}.
  628. */
  629. final int type;
  630. /** The number of modifications to the backing Map that we know about. */
  631. int knownMod = modCount;
  632. /** The number of elements remaining to be returned by next(). */
  633. int count = size;
  634. /** Location in the table. */
  635. int loc = table.length;
  636. /**
  637. * Construct a new Iterator with the supplied type.
  638. * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
  639. */
  640. IdentityIterator(int type)
  641. {
  642. this.type = type;
  643. }
  644. /**
  645. * Returns true if the Iterator has more elements.
  646. * @return true if there are more elements
  647. * @throws ConcurrentModificationException if the Map was modified
  648. */
  649. public boolean hasNext()
  650. {
  651. if (knownMod != modCount)
  652. throw new ConcurrentModificationException();
  653. return count > 0;
  654. }
  655. /**
  656. * Returns the next element in the Iterator's sequential view.
  657. * @return the next element
  658. * @throws ConcurrentModificationException if the Map was modified
  659. * @throws NoSuchElementException if there is none
  660. */
  661. public Object next()
  662. {
  663. if (knownMod != modCount)
  664. throw new ConcurrentModificationException();
  665. if (count == 0)
  666. throw new NoSuchElementException();
  667. count--;
  668. Object key;
  669. do
  670. {
  671. loc -= 2;
  672. key = table[loc];
  673. }
  674. while (key == emptyslot || key == tombstone);
  675. return type == KEYS ? key : (type == VALUES ? table[loc + 1]
  676. : new IdentityEntry(loc));
  677. }
  678. /**
  679. * Removes from the backing Map the last element which was fetched
  680. * with the <code>next()</code> method.
  681. *
  682. * @throws ConcurrentModificationException if the Map was modified
  683. * @throws IllegalStateException if called when there is no last element
  684. */
  685. public void remove()
  686. {
  687. if (knownMod != modCount)
  688. throw new ConcurrentModificationException();
  689. if (loc == table.length || table[loc] == tombstone)
  690. throw new IllegalStateException();
  691. modCount++;
  692. size--;
  693. table[loc] = tombstone;
  694. table[loc + 1] = tombstone;
  695. knownMod++;
  696. }
  697. } // class IdentityIterator
  698. /**
  699. * This class provides Map.Entry objects for IdentityHashMaps. The entry
  700. * is fail-fast, and will throw a ConcurrentModificationException if
  701. * the underlying map is modified, or if remove is called on the iterator
  702. * that generated this object. It is identity based, so it violates
  703. * the general contract of Map.Entry, and is probably unsuitable for
  704. * comparison to normal maps; but it works among other IdentityHashMaps.
  705. *
  706. * @author Eric Blake <ebb9@email.byu.edu>
  707. */
  708. private final class IdentityEntry implements Map.Entry
  709. {
  710. /** The location of this entry. */
  711. final int loc;
  712. /** The number of modifications to the backing Map that we know about. */
  713. final int knownMod = modCount;
  714. /**
  715. * Constructs the Entry.
  716. *
  717. * @param loc the location of this entry in table
  718. */
  719. IdentityEntry(int loc)
  720. {
  721. this.loc = loc;
  722. }
  723. /**
  724. * Compares the specified object with this entry, using identity
  725. * semantics. Note that this can lead to undefined results with
  726. * Entry objects created by normal maps.
  727. *
  728. * @param o the object to compare
  729. * @return true if it is equal
  730. * @throws ConcurrentModificationException if the entry was invalidated
  731. * by modifying the Map or calling Iterator.remove()
  732. */
  733. public boolean equals(Object o)
  734. {
  735. if (knownMod != modCount || table[loc] == tombstone)
  736. throw new ConcurrentModificationException();
  737. if (! (o instanceof Map.Entry))
  738. return false;
  739. Map.Entry e = (Map.Entry) o;
  740. return table[loc] == e.getKey() && table[loc + 1] == e.getValue();
  741. }
  742. /**
  743. * Returns the key of this entry.
  744. *
  745. * @return the key
  746. * @throws ConcurrentModificationException if the entry was invalidated
  747. * by modifying the Map or calling Iterator.remove()
  748. */
  749. public Object getKey()
  750. {
  751. if (knownMod != modCount || table[loc] == tombstone)
  752. throw new ConcurrentModificationException();
  753. return table[loc];
  754. }
  755. /**
  756. * Returns the value of this entry.
  757. *
  758. * @return the value
  759. * @throws ConcurrentModificationException if the entry was invalidated
  760. * by modifying the Map or calling Iterator.remove()
  761. */
  762. public Object getValue()
  763. {
  764. if (knownMod != modCount || table[loc] == tombstone)
  765. throw new ConcurrentModificationException();
  766. return table[loc + 1];
  767. }
  768. /**
  769. * Returns the hashcode of the entry, using identity semantics.
  770. * Note that this can lead to undefined results with Entry objects
  771. * created by normal maps.
  772. *
  773. * @return the hash code
  774. * @throws ConcurrentModificationException if the entry was invalidated
  775. * by modifying the Map or calling Iterator.remove()
  776. */
  777. public int hashCode()
  778. {
  779. if (knownMod != modCount || table[loc] == tombstone)
  780. throw new ConcurrentModificationException();
  781. return (System.identityHashCode(table[loc])
  782. ^ System.identityHashCode(table[loc + 1]));
  783. }
  784. /**
  785. * Replaces the value of this mapping, and returns the old value.
  786. *
  787. * @param value the new value
  788. * @return the old value
  789. * @throws ConcurrentModificationException if the entry was invalidated
  790. * by modifying the Map or calling Iterator.remove()
  791. */
  792. public Object setValue(Object value)
  793. {
  794. if (knownMod != modCount || table[loc] == tombstone)
  795. throw new ConcurrentModificationException();
  796. Object r = table[loc + 1];
  797. table[loc + 1] = value;
  798. return r;
  799. }
  800. /**
  801. * This provides a string representation of the entry. It is of the form
  802. * "key=value", where string concatenation is used on key and value.
  803. *
  804. * @return the string representation
  805. * @throws ConcurrentModificationException if the entry was invalidated
  806. * by modifying the Map or calling Iterator.remove()
  807. */
  808. public final String toString()
  809. {
  810. if (knownMod != modCount || table[loc] == tombstone)
  811. throw new ConcurrentModificationException();
  812. return table[loc] + "=" + table[loc + 1];
  813. }
  814. } // class IdentityEntry
  815. /**
  816. * Reads the object from a serial stream.
  817. *
  818. * @param s the stream to read from
  819. * @throws ClassNotFoundException if the underlying stream fails
  820. * @throws IOException if the underlying stream fails
  821. * @serialData expects the size (int), followed by that many key (Object)
  822. * and value (Object) pairs, with the pairs in no particular
  823. * order
  824. */
  825. private void readObject(ObjectInputStream s)
  826. throws IOException, ClassNotFoundException
  827. {
  828. s.defaultReadObject();
  829. int num = s.readInt();
  830. table = new Object[Math.max(num << 1, DEFAULT_CAPACITY) << 1];
  831. // Read key/value pairs.
  832. while (--num >= 0)
  833. put(s.readObject(), s.readObject());
  834. }
  835. /**
  836. * Writes the object to a serial stream.
  837. *
  838. * @param s the stream to write to
  839. * @throws IOException if the underlying stream fails
  840. * @serialData outputs the size (int), followed by that many key (Object)
  841. * and value (Object) pairs, with the pairs in no particular
  842. * order
  843. */
  844. private void writeObject(ObjectOutputStream s)
  845. throws IOException
  846. {
  847. s.defaultWriteObject();
  848. s.writeInt(size);
  849. for (int i = table.length - 2; i >= 0; i -= 2)
  850. {
  851. Object key = table[i];
  852. if (key != tombstone && key != emptyslot)
  853. {
  854. s.writeObject(key);
  855. s.writeObject(table[i + 1]);
  856. }
  857. }
  858. }
  859. }