PageRenderTime 80ms CodeModel.GetById 36ms RepoModel.GetById 2ms app.codeStats 0ms

/java/util/IdentityHashMap.java

https://github.com/penberg/classpath
Java | 990 lines | 456 code | 69 blank | 465 comment | 92 complexity | 0fc490f2fc550a52a0196c64cce03c8f MD5 | raw file
  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, 2004, 2005 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., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 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.IOException;
  34. import java.io.ObjectInputStream;
  35. import java.io.ObjectOutputStream;
  36. import java.io.Serializable;
  37. /**
  38. * This class provides a hashtable-backed implementation of the
  39. * Map interface, but uses object identity to do its hashing. In fact,
  40. * it uses object identity for comparing values, as well. It uses a
  41. * linear-probe hash table, which may have faster performance
  42. * than the chaining employed by HashMap.
  43. * <p>
  44. *
  45. * <em>WARNING: This is not a general purpose map. Because it uses
  46. * System.identityHashCode and ==, instead of hashCode and equals, for
  47. * comparison, it violated Map's general contract, and may cause
  48. * undefined behavior when compared to other maps which are not
  49. * IdentityHashMaps. This is designed only for the rare cases when
  50. * identity semantics are needed.</em> An example use is
  51. * topology-preserving graph transformations, such as deep cloning,
  52. * or as proxy object mapping such as in debugging.
  53. * <p>
  54. *
  55. * This map permits <code>null</code> keys and values, and does not
  56. * guarantee that elements will stay in the same order over time. The
  57. * basic operations (<code>get</code> and <code>put</code>) take
  58. * constant time, provided System.identityHashCode is decent. You can
  59. * tune the behavior by specifying the expected maximum size. As more
  60. * elements are added, the map may need to allocate a larger table,
  61. * which can be expensive.
  62. * <p>
  63. *
  64. * This implementation is unsynchronized. If you want multi-thread
  65. * access to be consistent, you must synchronize it, perhaps by using
  66. * <code>Collections.synchronizedMap(new IdentityHashMap(...));</code>.
  67. * The iterators are <i>fail-fast</i>, meaning that a structural modification
  68. * made to the map outside of an iterator's remove method cause the
  69. * iterator, and in the case of the entrySet, the Map.Entry, to
  70. * fail with a {@link ConcurrentModificationException}.
  71. *
  72. * @author Tom Tromey (tromey@redhat.com)
  73. * @author Eric Blake (ebb9@email.byu.edu)
  74. * @see System#identityHashCode(Object)
  75. * @see Collection
  76. * @see Map
  77. * @see HashMap
  78. * @see TreeMap
  79. * @see LinkedHashMap
  80. * @see WeakHashMap
  81. * @since 1.4
  82. * @status updated to 1.4
  83. */
  84. public class IdentityHashMap<K,V> extends AbstractMap<K,V>
  85. implements Map<K,V>, Serializable, Cloneable
  86. {
  87. /** The default capacity. */
  88. private static final int DEFAULT_CAPACITY = 21;
  89. /**
  90. * This object is used to mark a slot whose key or value is 'null'.
  91. * This is more efficient than using a special value to mark an empty
  92. * slot, because null entries are rare, empty slots are common, and
  93. * the JVM will clear new arrays for us.
  94. * Package visible for use by nested classes.
  95. */
  96. static final Object nullslot = new Object();
  97. /**
  98. * Compatible with JDK 1.4.
  99. */
  100. private static final long serialVersionUID = 8188218128353913216L;
  101. /**
  102. * The number of mappings in the table. Package visible for use by nested
  103. * classes.
  104. * @serial
  105. */
  106. int size;
  107. /**
  108. * The table itself. Package visible for use by nested classes.
  109. */
  110. transient Object[] table;
  111. /**
  112. * The number of structural modifications made so far. Package visible for
  113. * use by nested classes.
  114. */
  115. transient int modCount;
  116. /**
  117. * The cache for {@link #entrySet()}.
  118. */
  119. private transient Set<Map.Entry<K,V>> entries;
  120. /**
  121. * The threshold for rehashing, which is 75% of (table.length / 2).
  122. */
  123. private transient int threshold;
  124. /**
  125. * Create a new IdentityHashMap with the default capacity (21 entries).
  126. */
  127. public IdentityHashMap()
  128. {
  129. this(DEFAULT_CAPACITY);
  130. }
  131. /**
  132. * Create a new IdentityHashMap with the indicated number of
  133. * entries. If the number of elements added to this hash map
  134. * exceeds this maximum, the map will grow itself; however, that
  135. * incurs a performance penalty.
  136. *
  137. * @param max initial size
  138. * @throws IllegalArgumentException if max is negative
  139. */
  140. public IdentityHashMap(int max)
  141. {
  142. if (max < 0)
  143. throw new IllegalArgumentException();
  144. // Need at least two slots, or hash() will break.
  145. if (max < 2)
  146. max = 2;
  147. table = new Object[max << 1];
  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<? extends K, ? extends V> 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, null);
  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. key = xform(key);
  205. return key == table[hash(key)];
  206. }
  207. /**
  208. * Returns true if this HashMap contains the value. Unlike normal maps,
  209. * this test uses <code>entry == value</code> instead of
  210. * <code>entry == null ? value == null : entry.equals(value)</code>.
  211. *
  212. * @param value the value to search for in this HashMap
  213. * @return true if at least one key maps to the value
  214. * @see #containsKey(Object)
  215. */
  216. public boolean containsValue(Object value)
  217. {
  218. value = xform(value);
  219. for (int i = table.length - 1; i > 0; i -= 2)
  220. if (table[i] == value)
  221. return true;
  222. return false;
  223. }
  224. /**
  225. * Returns a "set view" of this Map's entries. The set is backed by
  226. * the Map, so changes in one show up in the other. The set supports
  227. * element removal, but not element addition.
  228. * <p>
  229. *
  230. * <em>The semantics of this set, and of its contained entries, are
  231. * different from the contract of Set and Map.Entry in order to make
  232. * IdentityHashMap work. This means that while you can compare these
  233. * objects between IdentityHashMaps, comparing them with regular sets
  234. * or entries is likely to have undefined behavior.</em> The entries
  235. * in this set are reference-based, rather than the normal object
  236. * equality. Therefore, <code>e1.equals(e2)</code> returns
  237. * <code>e1.getKey() == e2.getKey() && e1.getValue() == e2.getValue()</code>,
  238. * and <code>e.hashCode()</code> returns
  239. * <code>System.identityHashCode(e.getKey()) ^
  240. * System.identityHashCode(e.getValue())</code>.
  241. * <p>
  242. *
  243. * Note that the iterators for all three views, from keySet(), entrySet(),
  244. * and values(), traverse the Map in the same sequence.
  245. *
  246. * @return a set view of the entries
  247. * @see #keySet()
  248. * @see #values()
  249. * @see Map.Entry
  250. */
  251. public Set<Map.Entry<K,V>> entrySet()
  252. {
  253. if (entries == null)
  254. entries = new AbstractSet<Map.Entry<K,V>>()
  255. {
  256. public int size()
  257. {
  258. return size;
  259. }
  260. public Iterator<Map.Entry<K,V>> iterator()
  261. {
  262. return new IdentityIterator<Map.Entry<K,V>>(ENTRIES);
  263. }
  264. public void clear()
  265. {
  266. IdentityHashMap.this.clear();
  267. }
  268. public boolean contains(Object o)
  269. {
  270. if (! (o instanceof Map.Entry))
  271. return false;
  272. Map.Entry m = (Map.Entry) o;
  273. Object value = xform(m.getValue());
  274. Object key = xform(m.getKey());
  275. return value == table[hash(key) + 1];
  276. }
  277. public int hashCode()
  278. {
  279. return IdentityHashMap.this.hashCode();
  280. }
  281. public boolean remove(Object o)
  282. {
  283. if (! (o instanceof Map.Entry))
  284. return false;
  285. Object key = xform(((Map.Entry) o).getKey());
  286. int h = hash(key);
  287. if (table[h] == key)
  288. {
  289. size--;
  290. modCount++;
  291. IdentityHashMap.this.removeAtIndex(h);
  292. return true;
  293. }
  294. return false;
  295. }
  296. };
  297. return entries;
  298. }
  299. /**
  300. * Compares two maps for equality. This returns true only if both maps
  301. * have the same reference-identity comparisons. While this returns
  302. * <code>this.entrySet().equals(m.entrySet())</code> as specified by Map,
  303. * this will not work with normal maps, since the entry set compares
  304. * with == instead of .equals.
  305. *
  306. * @param o the object to compare to
  307. * @return true if it is equal
  308. */
  309. public boolean equals(Object o)
  310. {
  311. // Why did Sun specify this one? The superclass does the right thing.
  312. return super.equals(o);
  313. }
  314. /**
  315. * Return the value in this Map associated with the supplied key, or
  316. * <code>null</code> if the key maps to nothing.
  317. *
  318. * <p>NOTE: Since the value could also be null, you must use
  319. * containsKey to see if this key actually maps to something.
  320. * Unlike normal maps, this tests for the key with <code>entry ==
  321. * key</code> instead of <code>entry == null ? key == null :
  322. * entry.equals(key)</code>.
  323. *
  324. * @param key the key for which to fetch an associated value
  325. * @return what the key maps to, if present
  326. * @see #put(Object, Object)
  327. * @see #containsKey(Object)
  328. */
  329. public V get(Object key)
  330. {
  331. key = xform(key);
  332. int h = hash(key);
  333. return (V) (table[h] == key ? unxform(table[h + 1]) : null);
  334. }
  335. /**
  336. * Returns the hashcode of this map. This guarantees that two
  337. * IdentityHashMaps that compare with equals() will have the same hash code,
  338. * but may break with comparison to normal maps since it uses
  339. * System.identityHashCode() instead of hashCode().
  340. *
  341. * @return the hash code
  342. */
  343. public int hashCode()
  344. {
  345. int hash = 0;
  346. for (int i = table.length - 2; i >= 0; i -= 2)
  347. {
  348. Object key = table[i];
  349. if (key == null)
  350. continue;
  351. // FIXME: this is a lame computation.
  352. hash += (System.identityHashCode(unxform(key))
  353. ^ System.identityHashCode(unxform(table[i + 1])));
  354. }
  355. return hash;
  356. }
  357. /**
  358. * Returns true if there are no key-value mappings currently in this Map
  359. * @return <code>size() == 0</code>
  360. */
  361. public boolean isEmpty()
  362. {
  363. return size == 0;
  364. }
  365. /**
  366. * Returns a "set view" of this Map's keys. The set is backed by the
  367. * Map, so changes in one show up in the other. The set supports
  368. * element removal, but not element addition.
  369. * <p>
  370. *
  371. * <em>The semantics of this set are different from the contract of Set
  372. * in order to make IdentityHashMap work. This means that while you can
  373. * compare these objects between IdentityHashMaps, comparing them with
  374. * regular sets is likely to have undefined behavior.</em> The hashCode
  375. * of the set is the sum of the identity hash codes, instead of the
  376. * regular hashCodes, and equality is determined by reference instead
  377. * of by the equals method.
  378. * <p>
  379. *
  380. * @return a set view of the keys
  381. * @see #values()
  382. * @see #entrySet()
  383. */
  384. public Set<K> keySet()
  385. {
  386. if (keys == null)
  387. keys = new AbstractSet<K>()
  388. {
  389. public int size()
  390. {
  391. return size;
  392. }
  393. public Iterator<K> iterator()
  394. {
  395. return new IdentityIterator<K>(KEYS);
  396. }
  397. public void clear()
  398. {
  399. IdentityHashMap.this.clear();
  400. }
  401. public boolean contains(Object o)
  402. {
  403. return containsKey(o);
  404. }
  405. public int hashCode()
  406. {
  407. int hash = 0;
  408. for (int i = table.length - 2; i >= 0; i -= 2)
  409. {
  410. Object key = table[i];
  411. if (key == null)
  412. continue;
  413. hash += System.identityHashCode(unxform(key));
  414. }
  415. return hash;
  416. }
  417. public boolean remove(Object o)
  418. {
  419. o = xform(o);
  420. int h = hash(o);
  421. if (table[h] == o)
  422. {
  423. size--;
  424. modCount++;
  425. removeAtIndex(h);
  426. return true;
  427. }
  428. return false;
  429. }
  430. };
  431. return keys;
  432. }
  433. /**
  434. * Puts the supplied value into the Map, mapped by the supplied key.
  435. * The value may be retrieved by any object which <code>equals()</code>
  436. * this key. NOTE: Since the prior value could also be null, you must
  437. * first use containsKey if you want to see if you are replacing the
  438. * key's mapping. Unlike normal maps, this tests for the key
  439. * with <code>entry == key</code> instead of
  440. * <code>entry == null ? key == null : entry.equals(key)</code>.
  441. *
  442. * @param key the key used to locate the value
  443. * @param value the value to be stored in the HashMap
  444. * @return the prior mapping of the key, or null if there was none
  445. * @see #get(Object)
  446. */
  447. public V put(K key, V value)
  448. {
  449. key = (K) xform(key);
  450. value = (V) xform(value);
  451. // We don't want to rehash if we're overwriting an existing slot.
  452. int h = hash(key);
  453. if (table[h] == key)
  454. {
  455. V r = (V) unxform(table[h + 1]);
  456. table[h + 1] = value;
  457. return r;
  458. }
  459. // Rehash if the load factor is too high.
  460. if (size > threshold)
  461. {
  462. Object[] old = table;
  463. // This isn't necessarily prime, but it is an odd number of key/value
  464. // slots, which has a higher probability of fewer collisions.
  465. table = new Object[(old.length * 2) + 2];
  466. size = 0;
  467. threshold = (table.length >>> 3) * 3;
  468. for (int i = old.length - 2; i >= 0; i -= 2)
  469. {
  470. K oldkey = (K) old[i];
  471. if (oldkey != null)
  472. {
  473. h = hash(oldkey);
  474. table[h] = oldkey;
  475. table[h + 1] = old[i + 1];
  476. ++size;
  477. // No need to update modCount here, we'll do it
  478. // just after the loop.
  479. }
  480. }
  481. // Now that we've resize, recompute the hash value.
  482. h = hash(key);
  483. }
  484. // At this point, we add a new mapping.
  485. modCount++;
  486. size++;
  487. table[h] = key;
  488. table[h + 1] = value;
  489. return null;
  490. }
  491. /**
  492. * Copies all of the mappings from the specified map to this. If a key
  493. * is already in this map, its value is replaced.
  494. *
  495. * @param m the map to copy
  496. * @throws NullPointerException if m is null
  497. */
  498. public void putAll(Map<? extends K, ? extends V> m)
  499. {
  500. // Why did Sun specify this one? The superclass does the right thing.
  501. super.putAll(m);
  502. }
  503. /**
  504. * Remove the element at index and update the table to compensate.
  505. * This is package-private for use by inner classes.
  506. * @param i index of the removed element
  507. */
  508. final void removeAtIndex(int i)
  509. {
  510. // This is Algorithm R from Knuth, section 6.4.
  511. // Variable names are taken directly from the text.
  512. while (true)
  513. {
  514. table[i] = null;
  515. table[i + 1] = null;
  516. int j = i;
  517. int r;
  518. do
  519. {
  520. i -= 2;
  521. if (i < 0)
  522. i = table.length - 2;
  523. Object key = table[i];
  524. if (key == null)
  525. return;
  526. r = Math.abs(System.identityHashCode(key)
  527. % (table.length >> 1)) << 1;
  528. }
  529. while ((i <= r && r < j)
  530. || (r < j && j < i)
  531. || (j < i && i <= r));
  532. table[j] = table[i];
  533. table[j + 1] = table[i + 1];
  534. }
  535. }
  536. /**
  537. * Removes from the HashMap and returns the value which is mapped by
  538. * the supplied key. If the key maps to nothing, then the HashMap
  539. * remains unchanged, and <code>null</code> is returned.
  540. *
  541. * NOTE: Since the value could also be null, you must use
  542. * containsKey to see if you are actually removing a mapping.
  543. * Unlike normal maps, this tests for the key with <code>entry ==
  544. * key</code> instead of <code>entry == null ? key == null :
  545. * entry.equals(key)</code>.
  546. *
  547. * @param key the key used to locate the value to remove
  548. * @return whatever the key mapped to, if present
  549. */
  550. public V remove(Object key)
  551. {
  552. key = xform(key);
  553. int h = hash(key);
  554. if (table[h] == key)
  555. {
  556. modCount++;
  557. size--;
  558. Object r = unxform(table[h + 1]);
  559. removeAtIndex(h);
  560. return (V) r;
  561. }
  562. return null;
  563. }
  564. /**
  565. * Returns the number of kay-value mappings currently in this Map
  566. * @return the size
  567. */
  568. public int size()
  569. {
  570. return size;
  571. }
  572. /**
  573. * Returns a "collection view" (or "bag view") of this Map's values.
  574. * The collection is backed by the Map, so changes in one show up
  575. * in the other. The collection supports element removal, but not element
  576. * addition.
  577. * <p>
  578. *
  579. * <em>The semantics of this set are different from the contract of
  580. * Collection in order to make IdentityHashMap work. This means that
  581. * while you can compare these objects between IdentityHashMaps, comparing
  582. * them with regular sets is likely to have undefined behavior.</em>
  583. * Likewise, contains and remove go by == instead of equals().
  584. * <p>
  585. *
  586. * @return a bag view of the values
  587. * @see #keySet()
  588. * @see #entrySet()
  589. */
  590. public Collection<V> values()
  591. {
  592. if (values == null)
  593. values = new AbstractCollection<V>()
  594. {
  595. public int size()
  596. {
  597. return size;
  598. }
  599. public Iterator<V> iterator()
  600. {
  601. return new IdentityIterator<V>(VALUES);
  602. }
  603. public void clear()
  604. {
  605. IdentityHashMap.this.clear();
  606. }
  607. public boolean remove(Object o)
  608. {
  609. o = xform(o);
  610. // This approach may look strange, but it is ok.
  611. for (int i = table.length - 1; i > 0; i -= 2)
  612. if (table[i] == o)
  613. {
  614. modCount++;
  615. size--;
  616. IdentityHashMap.this.removeAtIndex(i - 1);
  617. return true;
  618. }
  619. return false;
  620. }
  621. };
  622. return values;
  623. }
  624. /**
  625. * Transform a reference from its external form to its internal form.
  626. * This is package-private for use by inner classes.
  627. */
  628. final Object xform(Object o)
  629. {
  630. if (o == null)
  631. o = nullslot;
  632. return o;
  633. }
  634. /**
  635. * Transform a reference from its internal form to its external form.
  636. * This is package-private for use by inner classes.
  637. */
  638. final Object unxform(Object o)
  639. {
  640. if (o == nullslot)
  641. o = null;
  642. return o;
  643. }
  644. /**
  645. * Helper method which computes the hash code, then traverses the table
  646. * until it finds the key, or the spot where the key would go. the key
  647. * must already be in its internal form.
  648. *
  649. * @param key the key to check
  650. * @return the index where the key belongs
  651. * @see #IdentityHashMap(int)
  652. * @see #put(Object, Object)
  653. */
  654. // Package visible for use by nested classes.
  655. final int hash(Object key)
  656. {
  657. int h = Math.abs(System.identityHashCode(key) % (table.length >> 1)) << 1;
  658. while (true)
  659. {
  660. // By requiring at least 2 key/value slots, and rehashing at 75%
  661. // capacity, we guarantee that there will always be either an empty
  662. // slot somewhere in the table.
  663. if (table[h] == key || table[h] == null)
  664. return h;
  665. // We use linear probing as it is friendlier to the cache and
  666. // it lets us efficiently remove entries.
  667. h -= 2;
  668. if (h < 0)
  669. h = table.length - 2;
  670. }
  671. }
  672. /**
  673. * This class allows parameterized iteration over IdentityHashMaps. Based
  674. * on its construction, it returns the key or value of a mapping, or
  675. * creates the appropriate Map.Entry object with the correct fail-fast
  676. * semantics and identity comparisons.
  677. *
  678. * @author Tom Tromey (tromey@redhat.com)
  679. * @author Eric Blake (ebb9@email.byu.edu)
  680. */
  681. private class IdentityIterator<I> implements Iterator<I>
  682. {
  683. /**
  684. * The type of this Iterator: {@link #KEYS}, {@link #VALUES},
  685. * or {@link #ENTRIES}.
  686. */
  687. final int type;
  688. /** The number of modifications to the backing Map that we know about. */
  689. int knownMod = modCount;
  690. /** The number of elements remaining to be returned by next(). */
  691. int count = size;
  692. /** Location in the table. */
  693. int loc = table.length;
  694. /**
  695. * Construct a new Iterator with the supplied type.
  696. * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
  697. */
  698. IdentityIterator(int type)
  699. {
  700. this.type = type;
  701. }
  702. /**
  703. * Returns true if the Iterator has more elements.
  704. * @return true if there are more elements
  705. */
  706. public boolean hasNext()
  707. {
  708. return count > 0;
  709. }
  710. /**
  711. * Returns the next element in the Iterator's sequential view.
  712. * @return the next element
  713. * @throws ConcurrentModificationException if the Map was modified
  714. * @throws NoSuchElementException if there is none
  715. */
  716. public I next()
  717. {
  718. if (knownMod != modCount)
  719. throw new ConcurrentModificationException();
  720. if (count == 0)
  721. throw new NoSuchElementException();
  722. count--;
  723. Object key;
  724. do
  725. {
  726. loc -= 2;
  727. key = table[loc];
  728. }
  729. while (key == null);
  730. return (I) (type == KEYS ? unxform(key)
  731. : (type == VALUES ? unxform(table[loc + 1])
  732. : new IdentityEntry(loc)));
  733. }
  734. /**
  735. * Removes from the backing Map the last element which was fetched
  736. * with the <code>next()</code> method.
  737. *
  738. * @throws ConcurrentModificationException if the Map was modified
  739. * @throws IllegalStateException if called when there is no last element
  740. */
  741. public void remove()
  742. {
  743. if (knownMod != modCount)
  744. throw new ConcurrentModificationException();
  745. if (loc == table.length)
  746. throw new IllegalStateException();
  747. modCount++;
  748. size--;
  749. removeAtIndex(loc);
  750. knownMod++;
  751. }
  752. } // class IdentityIterator
  753. /**
  754. * This class provides Map.Entry objects for IdentityHashMaps. The entry
  755. * is fail-fast, and will throw a ConcurrentModificationException if
  756. * the underlying map is modified, or if remove is called on the iterator
  757. * that generated this object. It is identity based, so it violates
  758. * the general contract of Map.Entry, and is probably unsuitable for
  759. * comparison to normal maps; but it works among other IdentityHashMaps.
  760. *
  761. * @author Eric Blake (ebb9@email.byu.edu)
  762. */
  763. private final class IdentityEntry<EK,EV> implements Map.Entry<EK,EV>
  764. {
  765. /** The location of this entry. */
  766. final int loc;
  767. /** The number of modifications to the backing Map that we know about. */
  768. final int knownMod = modCount;
  769. /**
  770. * Constructs the Entry.
  771. *
  772. * @param loc the location of this entry in table
  773. */
  774. IdentityEntry(int loc)
  775. {
  776. this.loc = loc;
  777. }
  778. /**
  779. * Compares the specified object with this entry, using identity
  780. * semantics. Note that this can lead to undefined results with
  781. * Entry objects created by normal maps.
  782. *
  783. * @param o the object to compare
  784. * @return true if it is equal
  785. * @throws ConcurrentModificationException if the entry was invalidated
  786. * by modifying the Map or calling Iterator.remove()
  787. */
  788. public boolean equals(Object o)
  789. {
  790. if (knownMod != modCount)
  791. throw new ConcurrentModificationException();
  792. if (! (o instanceof Map.Entry))
  793. return false;
  794. Map.Entry e = (Map.Entry) o;
  795. return table[loc] == xform(e.getKey())
  796. && table[loc + 1] == xform(e.getValue());
  797. }
  798. /**
  799. * Returns the key of this entry.
  800. *
  801. * @return the key
  802. * @throws ConcurrentModificationException if the entry was invalidated
  803. * by modifying the Map or calling Iterator.remove()
  804. */
  805. public EK getKey()
  806. {
  807. if (knownMod != modCount)
  808. throw new ConcurrentModificationException();
  809. return (EK) unxform(table[loc]);
  810. }
  811. /**
  812. * Returns the value of this entry.
  813. *
  814. * @return the value
  815. * @throws ConcurrentModificationException if the entry was invalidated
  816. * by modifying the Map or calling Iterator.remove()
  817. */
  818. public EV getValue()
  819. {
  820. if (knownMod != modCount)
  821. throw new ConcurrentModificationException();
  822. return (EV) unxform(table[loc + 1]);
  823. }
  824. /**
  825. * Returns the hashcode of the entry, using identity semantics.
  826. * Note that this can lead to undefined results with Entry objects
  827. * created by normal maps.
  828. *
  829. * @return the hash code
  830. * @throws ConcurrentModificationException if the entry was invalidated
  831. * by modifying the Map or calling Iterator.remove()
  832. */
  833. public int hashCode()
  834. {
  835. if (knownMod != modCount)
  836. throw new ConcurrentModificationException();
  837. return (System.identityHashCode(unxform(table[loc]))
  838. ^ System.identityHashCode(unxform(table[loc + 1])));
  839. }
  840. /**
  841. * Replaces the value of this mapping, and returns the old value.
  842. *
  843. * @param value the new value
  844. * @return the old value
  845. * @throws ConcurrentModificationException if the entry was invalidated
  846. * by modifying the Map or calling Iterator.remove()
  847. */
  848. public EV setValue(EV value)
  849. {
  850. if (knownMod != modCount)
  851. throw new ConcurrentModificationException();
  852. EV r = (EV) unxform(table[loc + 1]);
  853. table[loc + 1] = xform(value);
  854. return r;
  855. }
  856. /**
  857. * This provides a string representation of the entry. It is of the form
  858. * "key=value", where string concatenation is used on key and value.
  859. *
  860. * @return the string representation
  861. * @throws ConcurrentModificationException if the entry was invalidated
  862. * by modifying the Map or calling Iterator.remove()
  863. */
  864. public String toString()
  865. {
  866. if (knownMod != modCount)
  867. throw new ConcurrentModificationException();
  868. return unxform(table[loc]) + "=" + unxform(table[loc + 1]);
  869. }
  870. } // class IdentityEntry
  871. /**
  872. * Reads the object from a serial stream.
  873. *
  874. * @param s the stream to read from
  875. * @throws ClassNotFoundException if the underlying stream fails
  876. * @throws IOException if the underlying stream fails
  877. * @serialData expects the size (int), followed by that many key (Object)
  878. * and value (Object) pairs, with the pairs in no particular
  879. * order
  880. */
  881. private void readObject(ObjectInputStream s)
  882. throws IOException, ClassNotFoundException
  883. {
  884. s.defaultReadObject();
  885. int num = s.readInt();
  886. table = new Object[Math.max(num << 1, DEFAULT_CAPACITY) << 1];
  887. // Read key/value pairs.
  888. while (--num >= 0)
  889. put((K) s.readObject(), (V) s.readObject());
  890. }
  891. /**
  892. * Writes the object to a serial stream.
  893. *
  894. * @param s the stream to write to
  895. * @throws IOException if the underlying stream fails
  896. * @serialData outputs the size (int), followed by that many key (Object)
  897. * and value (Object) pairs, with the pairs in no particular
  898. * order
  899. */
  900. private void writeObject(ObjectOutputStream s)
  901. throws IOException
  902. {
  903. s.defaultWriteObject();
  904. s.writeInt(size);
  905. for (int i = table.length - 2; i >= 0; i -= 2)
  906. {
  907. Object key = table[i];
  908. if (key != null)
  909. {
  910. s.writeObject(unxform(key));
  911. s.writeObject(unxform(table[i + 1]));
  912. }
  913. }
  914. }
  915. }