AbstractMap.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /* AbstractMap.java -- Abstract implementation of most of Map
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. /**
  33. * An abstract implementation of Map to make it easier to create your own
  34. * implementations. In order to create an unmodifiable Map, subclass
  35. * AbstractMap and implement the <code>entrySet</code> (usually via an
  36. * AbstractSet). To make it modifiable, also implement <code>put</code>,
  37. * and have <code>entrySet().iterator()</code> support <code>remove</code>.
  38. * <p>
  39. *
  40. * It is recommended that classes which extend this support at least the
  41. * no-argument constructor, and a constructor which accepts another Map.
  42. * Further methods in this class may be overridden if you have a more
  43. * efficient implementation.
  44. *
  45. * @author Original author unknown
  46. * @author Bryce McKinlay
  47. * @author Eric Blake <ebb9@email.byu.edu>
  48. * @see Map
  49. * @see Collection
  50. * @see HashMap
  51. * @see LinkedHashMap
  52. * @see TreeMap
  53. * @see WeakHashMap
  54. * @see IdentityHashMap
  55. * @since 1.2
  56. * @status updated to 1.4
  57. */
  58. public abstract class AbstractMap implements Map
  59. {
  60. /** An "enum" of iterator types. */
  61. // Package visible for use by subclasses.
  62. static final int KEYS = 0,
  63. VALUES = 1,
  64. ENTRIES = 2;
  65. /**
  66. * The cache for {@link #keySet()}.
  67. */
  68. // Package visible for use by subclasses.
  69. Set keys;
  70. /**
  71. * The cache for {@link #values()}.
  72. */
  73. // Package visible for use by subclasses.
  74. Collection values;
  75. /**
  76. * The main constructor, for use by subclasses.
  77. */
  78. protected AbstractMap()
  79. {
  80. }
  81. /**
  82. * Remove all entries from this Map (optional operation). This default
  83. * implementation calls entrySet().clear(). NOTE: If the entry set does
  84. * not permit clearing, then this will fail, too. Subclasses often
  85. * override this for efficiency. Your implementation of entrySet() should
  86. * not call <code>AbstractMap.clear</code> unless you want an infinite loop.
  87. *
  88. * @throws UnsupportedOperationException if <code>entrySet().clear()</code>
  89. * does not support clearing.
  90. * @see Set#clear()
  91. */
  92. public void clear()
  93. {
  94. entrySet().clear();
  95. }
  96. /**
  97. * Create a shallow copy of this Map, no keys or values are copied. The
  98. * default implementation simply calls <code>super.clone()</code>.
  99. *
  100. * @return the shallow clone
  101. * @throws CloneNotSupportedException if a subclass is not Cloneable
  102. * @see Cloneable
  103. * @see Object#clone()
  104. */
  105. protected Object clone() throws CloneNotSupportedException
  106. {
  107. AbstractMap copy = (AbstractMap) super.clone();
  108. // Clear out the caches; they are stale.
  109. copy.keys = null;
  110. copy.values = null;
  111. return copy;
  112. }
  113. /**
  114. * Returns true if this contains a mapping for the given key. This
  115. * implementation does a linear search, O(n), over the
  116. * <code>entrySet()</code>, returning <code>true</code> if a match
  117. * is found, <code>false</code> if the iteration ends. Many subclasses
  118. * can implement this more efficiently.
  119. *
  120. * @param key the key to search for
  121. * @return true if the map contains the key
  122. * @throws NullPointerException if key is <code>null</code> but the map
  123. * does not permit null keys
  124. * @see #containsValue(Object)
  125. */
  126. public boolean containsKey(Object key)
  127. {
  128. Iterator entries = entrySet().iterator();
  129. int pos = size();
  130. while (--pos >= 0)
  131. if (equals(key, ((Map.Entry) entries.next()).getKey()))
  132. return true;
  133. return false;
  134. }
  135. /**
  136. * Returns true if this contains at least one mapping with the given value.
  137. * This implementation does a linear search, O(n), over the
  138. * <code>entrySet()</code>, returning <code>true</code> if a match
  139. * is found, <code>false</code> if the iteration ends. A match is
  140. * defined as <code>(value == null ? v == null : value.equals(v))</code>
  141. * Subclasses are unlikely to implement this more efficiently.
  142. *
  143. * @param value the value to search for
  144. * @return true if the map contains the value
  145. * @see #containsKey(Object)
  146. */
  147. public boolean containsValue(Object value)
  148. {
  149. Iterator entries = entrySet().iterator();
  150. int pos = size();
  151. while (--pos >= 0)
  152. if (equals(value, ((Map.Entry) entries.next()).getValue()))
  153. return true;
  154. return false;
  155. }
  156. /**
  157. * Returns a set view of the mappings in this Map. Each element in the
  158. * set must be an implementation of Map.Entry. The set is backed by
  159. * the map, so that changes in one show up in the other. Modifications
  160. * made while an iterator is in progress cause undefined behavior. If
  161. * the set supports removal, these methods must be valid:
  162. * <code>Iterator.remove</code>, <code>Set.remove</code>,
  163. * <code>removeAll</code>, <code>retainAll</code>, and <code>clear</code>.
  164. * Element addition is not supported via this set.
  165. *
  166. * @return the entry set
  167. * @see Map.Entry
  168. */
  169. public abstract Set entrySet();
  170. /**
  171. * Compares the specified object with this map for equality. Returns
  172. * <code>true</code> if the other object is a Map with the same mappings,
  173. * that is,<br>
  174. * <code>o instanceof Map && entrySet().equals(((Map) o).entrySet();</code>
  175. *
  176. * @param o the object to be compared
  177. * @return true if the object equals this map
  178. * @see Set#equals(Object)
  179. */
  180. public boolean equals(Object o)
  181. {
  182. return (o == this ||
  183. (o instanceof Map &&
  184. entrySet().equals(((Map) o).entrySet())));
  185. }
  186. /**
  187. * Returns the value mapped by the given key. Returns <code>null</code> if
  188. * there is no mapping. However, in Maps that accept null values, you
  189. * must rely on <code>containsKey</code> to determine if a mapping exists.
  190. * This iteration takes linear time, searching entrySet().iterator() of
  191. * the key. Many implementations override this method.
  192. *
  193. * @param key the key to look up
  194. * @return the value associated with the key, or null if key not in map
  195. * @throws NullPointerException if this map does not accept null keys
  196. * @see #containsKey(Object)
  197. */
  198. public Object get(Object key)
  199. {
  200. Iterator entries = entrySet().iterator();
  201. int pos = size();
  202. while (--pos >= 0)
  203. {
  204. Map.Entry entry = (Map.Entry) entries.next();
  205. if (equals(key, entry.getKey()))
  206. return entry.getValue();
  207. }
  208. return null;
  209. }
  210. /**
  211. * Returns the hash code for this map. As defined in Map, this is the sum
  212. * of all hashcodes for each Map.Entry object in entrySet, or basically
  213. * entrySet().hashCode().
  214. *
  215. * @return the hash code
  216. * @see Map.Entry#hashCode()
  217. * @see Set#hashCode()
  218. */
  219. public int hashCode()
  220. {
  221. return entrySet().hashCode();
  222. }
  223. /**
  224. * Returns true if the map contains no mappings. This is implemented by
  225. * <code>size() == 0</code>.
  226. *
  227. * @return true if the map is empty
  228. * @see #size()
  229. */
  230. public boolean isEmpty()
  231. {
  232. return size() == 0;
  233. }
  234. /**
  235. * Returns a set view of this map's keys. The set is backed by the map,
  236. * so changes in one show up in the other. Modifications while an iteration
  237. * is in progress produce undefined behavior. The set supports removal
  238. * if entrySet() does, but does not support element addition.
  239. * <p>
  240. *
  241. * This implementation creates an AbstractSet, where the iterator wraps
  242. * the entrySet iterator, size defers to the Map's size, and contains
  243. * defers to the Map's containsKey. The set is created on first use, and
  244. * returned on subsequent uses, although since no synchronization occurs,
  245. * there is a slight possibility of creating two sets.
  246. *
  247. * @return a Set view of the keys
  248. * @see Set#iterator()
  249. * @see #size()
  250. * @see #containsKey(Object)
  251. * @see #values()
  252. */
  253. public Set keySet()
  254. {
  255. if (keys == null)
  256. keys = new AbstractSet()
  257. {
  258. public int size()
  259. {
  260. return AbstractMap.this.size();
  261. }
  262. public boolean contains(Object key)
  263. {
  264. return containsKey(key);
  265. }
  266. public Iterator iterator()
  267. {
  268. return new Iterator()
  269. {
  270. private final Iterator map_iterator = entrySet().iterator();
  271. public boolean hasNext()
  272. {
  273. return map_iterator.hasNext();
  274. }
  275. public Object next()
  276. {
  277. return ((Map.Entry) map_iterator.next()).getKey();
  278. }
  279. public void remove()
  280. {
  281. map_iterator.remove();
  282. }
  283. };
  284. }
  285. };
  286. return keys;
  287. }
  288. /**
  289. * Associates the given key to the given value (optional operation). If the
  290. * map already contains the key, its value is replaced. This implementation
  291. * simply throws an UnsupportedOperationException. Be aware that in a map
  292. * that permits <code>null</code> values, a null return does not always
  293. * imply that the mapping was created.
  294. *
  295. * @param key the key to map
  296. * @param value the value to be mapped
  297. * @return the previous value of the key, or null if there was no mapping
  298. * @throws UnsupportedOperationException if the operation is not supported
  299. * @throws ClassCastException if the key or value is of the wrong type
  300. * @throws IllegalArgumentException if something about this key or value
  301. * prevents it from existing in this map
  302. * @throws NullPointerException if the map forbids null keys or values
  303. * @see #containsKey(Object)
  304. */
  305. public Object put(Object key, Object value)
  306. {
  307. throw new UnsupportedOperationException();
  308. }
  309. /**
  310. * Copies all entries of the given map to this one (optional operation). If
  311. * the map already contains a key, its value is replaced. This implementation
  312. * simply iterates over the map's entrySet(), calling <code>put</code>,
  313. * so it is not supported if puts are not.
  314. *
  315. * @param m the mapping to load into this map
  316. * @throws UnsupportedOperationException if the operation is not supported
  317. * @throws ClassCastException if a key or value is of the wrong type
  318. * @throws IllegalArgumentException if something about a key or value
  319. * prevents it from existing in this map
  320. * @throws NullPointerException if the map forbids null keys or values, or
  321. * if <code>m</code> is null.
  322. * @see #put(Object, Object)
  323. */
  324. public void putAll(Map m)
  325. {
  326. Iterator entries = m.entrySet().iterator();
  327. int pos = m.size();
  328. while (--pos >= 0)
  329. {
  330. Map.Entry entry = (Map.Entry) entries.next();
  331. put(entry.getKey(), entry.getValue());
  332. }
  333. }
  334. /**
  335. * Removes the mapping for this key if present (optional operation). This
  336. * implementation iterates over the entrySet searching for a matching
  337. * key, at which point it calls the iterator's <code>remove</code> method.
  338. * It returns the result of <code>getValue()</code> on the entry, if found,
  339. * or null if no entry is found. Note that maps which permit null values
  340. * may also return null if the key was removed. If the entrySet does not
  341. * support removal, this will also fail. This is O(n), so many
  342. * implementations override it for efficiency.
  343. *
  344. * @param key the key to remove
  345. * @return the value the key mapped to, or null if not present
  346. * @throws UnsupportedOperationException if deletion is unsupported
  347. * @see Iterator#remove()
  348. */
  349. public Object remove(Object key)
  350. {
  351. Iterator entries = entrySet().iterator();
  352. int pos = size();
  353. while (--pos >= 0)
  354. {
  355. Map.Entry entry = (Map.Entry) entries.next();
  356. if (equals(key, entry.getKey()))
  357. {
  358. // Must get the value before we remove it from iterator.
  359. Object r = entry.getValue();
  360. entries.remove();
  361. return r;
  362. }
  363. }
  364. return null;
  365. }
  366. /**
  367. * Returns the number of key-value mappings in the map. If there are more
  368. * than Integer.MAX_VALUE mappings, return Integer.MAX_VALUE. This is
  369. * implemented as <code>entrySet().size()</code>.
  370. *
  371. * @return the number of mappings
  372. * @see Set#size()
  373. */
  374. public int size()
  375. {
  376. return entrySet().size();
  377. }
  378. /**
  379. * Returns a String representation of this map. This is a listing of the
  380. * map entries (which are specified in Map.Entry as being
  381. * <code>getKey() + "=" + getValue()</code>), separated by a comma and
  382. * space (", "), and surrounded by braces ('{' and '}'). This implementation
  383. * uses a StringBuffer and iterates over the entrySet to build the String.
  384. * Note that this can fail with an exception if underlying keys or
  385. * values complete abruptly in toString().
  386. *
  387. * @return a String representation
  388. * @see Map.Entry#toString()
  389. */
  390. public String toString()
  391. {
  392. Iterator entries = entrySet().iterator();
  393. StringBuffer r = new StringBuffer("{");
  394. for (int pos = size(); pos > 0; pos--)
  395. {
  396. Map.Entry entry = (Map.Entry) entries.next();
  397. r.append(entry.getKey());
  398. r.append('=');
  399. r.append(entry.getValue());
  400. if (pos > 1)
  401. r.append(", ");
  402. }
  403. r.append("}");
  404. return r.toString();
  405. }
  406. /**
  407. * Returns a collection or bag view of this map's values. The collection
  408. * is backed by the map, so changes in one show up in the other.
  409. * Modifications while an iteration is in progress produce undefined
  410. * behavior. The collection supports removal if entrySet() does, but
  411. * does not support element addition.
  412. * <p>
  413. *
  414. * This implementation creates an AbstractCollection, where the iterator
  415. * wraps the entrySet iterator, size defers to the Map's size, and contains
  416. * defers to the Map's containsValue. The collection is created on first
  417. * use, and returned on subsequent uses, although since no synchronization
  418. * occurs, there is a slight possibility of creating two collections.
  419. *
  420. * @return a Collection view of the values
  421. * @see Collection#iterator()
  422. * @see #size()
  423. * @see #containsValue(Object)
  424. * @see #keySet()
  425. */
  426. public Collection values()
  427. {
  428. if (values == null)
  429. values = new AbstractCollection()
  430. {
  431. public int size()
  432. {
  433. return AbstractMap.this.size();
  434. }
  435. public boolean contains(Object value)
  436. {
  437. return containsValue(value);
  438. }
  439. public Iterator iterator()
  440. {
  441. return new Iterator()
  442. {
  443. private final Iterator map_iterator = entrySet().iterator();
  444. public boolean hasNext()
  445. {
  446. return map_iterator.hasNext();
  447. }
  448. public Object next()
  449. {
  450. return ((Map.Entry) map_iterator.next()).getValue();
  451. }
  452. public void remove()
  453. {
  454. map_iterator.remove();
  455. }
  456. };
  457. }
  458. };
  459. return values;
  460. }
  461. /**
  462. * Compare two objects according to Collection semantics.
  463. *
  464. * @param o1 the first object
  465. * @param o2 the second object
  466. * @return o1 == null ? o2 == null : o1.equals(o2)
  467. */
  468. // Package visible for use throughout java.util.
  469. // It may be inlined since it is final.
  470. static final boolean equals(Object o1, Object o2)
  471. {
  472. return o1 == null ? o2 == null : o1.equals(o2);
  473. }
  474. /**
  475. * Hash an object according to Collection semantics.
  476. *
  477. * @param o the object to hash
  478. * @return o1 == null ? 0 : o1.hashCode()
  479. */
  480. // Package visible for use throughout java.util.
  481. // It may be inlined since it is final.
  482. static final int hashCode(Object o)
  483. {
  484. return o == null ? 0 : o.hashCode();
  485. }
  486. /**
  487. * A class which implements Map.Entry. It is shared by HashMap, TreeMap,
  488. * Hashtable, and Collections. It is not specified by the JDK, but makes
  489. * life much easier.
  490. *
  491. * @author Jon Zeppieri
  492. * @author Eric Blake <ebb9@email.byu.edu>
  493. */
  494. // XXX - FIXME Use fully qualified implements as gcj 3.1 workaround.
  495. static class BasicMapEntry implements Map.Entry
  496. {
  497. /**
  498. * The key. Package visible for direct manipulation.
  499. */
  500. Object key;
  501. /**
  502. * The value. Package visible for direct manipulation.
  503. */
  504. Object value;
  505. /**
  506. * Basic constructor initializes the fields.
  507. * @param newKey the key
  508. * @param newValue the value
  509. */
  510. BasicMapEntry(Object newKey, Object newValue)
  511. {
  512. key = newKey;
  513. value = newValue;
  514. }
  515. /**
  516. * Compares the specified object with this entry. Returns true only if
  517. * the object is a mapping of identical key and value. In other words,
  518. * this must be:<br>
  519. * <pre>(o instanceof Map.Entry)
  520. * && (getKey() == null ? ((HashMap) o).getKey() == null
  521. * : getKey().equals(((HashMap) o).getKey()))
  522. * && (getValue() == null ? ((HashMap) o).getValue() == null
  523. * : getValue().equals(((HashMap) o).getValue()))</pre>
  524. *
  525. * @param o the object to compare
  526. * @return <code>true</code> if it is equal
  527. */
  528. public final boolean equals(Object o)
  529. {
  530. if (! (o instanceof Map.Entry))
  531. return false;
  532. // Optimize for our own entries.
  533. if (o instanceof BasicMapEntry)
  534. {
  535. BasicMapEntry e = (BasicMapEntry) o;
  536. return (AbstractMap.equals(key, e.key)
  537. && AbstractMap.equals(value, e.value));
  538. }
  539. Map.Entry e = (Map.Entry) o;
  540. return (AbstractMap.equals(key, e.getKey())
  541. && AbstractMap.equals(value, e.getValue()));
  542. }
  543. /**
  544. * Get the key corresponding to this entry.
  545. *
  546. * @return the key
  547. */
  548. public final Object getKey()
  549. {
  550. return key;
  551. }
  552. /**
  553. * Get the value corresponding to this entry. If you already called
  554. * Iterator.remove(), the behavior undefined, but in this case it works.
  555. *
  556. * @return the value
  557. */
  558. public final Object getValue()
  559. {
  560. return value;
  561. }
  562. /**
  563. * Returns the hash code of the entry. This is defined as the exclusive-or
  564. * of the hashcodes of the key and value (using 0 for null). In other
  565. * words, this must be:<br>
  566. * <pre>(getKey() == null ? 0 : getKey().hashCode())
  567. * ^ (getValue() == null ? 0 : getValue().hashCode())</pre>
  568. *
  569. * @return the hash code
  570. */
  571. public final int hashCode()
  572. {
  573. return (AbstractMap.hashCode(key) ^ AbstractMap.hashCode(value));
  574. }
  575. /**
  576. * Replaces the value with the specified object. This writes through
  577. * to the map, unless you have already called Iterator.remove(). It
  578. * may be overridden to restrict a null value.
  579. *
  580. * @param newVal the new value to store
  581. * @return the old value
  582. * @throws NullPointerException if the map forbids null values
  583. */
  584. public Object setValue(Object newVal)
  585. {
  586. Object r = value;
  587. value = newVal;
  588. return r;
  589. }
  590. /**
  591. * This provides a string representation of the entry. It is of the form
  592. * "key=value", where string concatenation is used on key and value.
  593. *
  594. * @return the string representation
  595. */
  596. public final String toString()
  597. {
  598. return key + "=" + value;
  599. }
  600. } // class BasicMapEntry
  601. }