1. /*
  2. * @(#)AbstractMap.java 1.34 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. import java.util.Map.Entry;
  9. /**
  10. * This class provides a skeletal implementation of the <tt>Map</tt>
  11. * interface, to minimize the effort required to implement this interface. <p>
  12. *
  13. * To implement an unmodifiable map, the programmer needs only to extend this
  14. * class and provide an implementation for the <tt>entrySet</tt> method, which
  15. * returns a set-view of the map's mappings. Typically, the returned set
  16. * will, in turn, be implemented atop <tt>AbstractSet</tt>. This set should
  17. * not support the <tt>add</tt> or <tt>remove</tt> methods, and its iterator
  18. * should not support the <tt>remove</tt> method.<p>
  19. *
  20. * To implement a modifiable map, the programmer must additionally override
  21. * this class's <tt>put</tt> method (which otherwise throws an
  22. * <tt>UnsupportedOperationException</tt>), and the iterator returned by
  23. * <tt>entrySet().iterator()</tt> must additionally implement its
  24. * <tt>remove</tt> method.<p>
  25. *
  26. * The programmer should generally provide a void (no argument) and map
  27. * constructor, as per the recommendation in the <tt>Map</tt> interface
  28. * specification.<p>
  29. *
  30. * The documentation for each non-abstract methods in this class describes its
  31. * implementation in detail. Each of these methods may be overridden if the
  32. * map being implemented admits a more efficient implementation.<p>
  33. *
  34. * This class is a member of the
  35. * <a href="{@docRoot}/../guide/collections/index.html">
  36. * Java Collections Framework</a>.
  37. *
  38. * @author Josh Bloch
  39. * @version 1.34, 01/23/03
  40. * @see Map
  41. * @see Collection
  42. * @since 1.2
  43. */
  44. public abstract class AbstractMap implements Map {
  45. /**
  46. * Sole constructor. (For invocation by subclass constructors, typically
  47. * implicit.)
  48. */
  49. protected AbstractMap() {
  50. }
  51. // Query Operations
  52. /**
  53. * Returns the number of key-value mappings in this map. If the map
  54. * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
  55. * <tt>Integer.MAX_VALUE</tt>.<p>
  56. *
  57. * This implementation returns <tt>entrySet().size()</tt>.
  58. *
  59. * @return the number of key-value mappings in this map.
  60. */
  61. public int size() {
  62. return entrySet().size();
  63. }
  64. /**
  65. * Returns <tt>true</tt> if this map contains no key-value mappings. <p>
  66. *
  67. * This implementation returns <tt>size() == 0</tt>.
  68. *
  69. * @return <tt>true</tt> if this map contains no key-value mappings.
  70. */
  71. public boolean isEmpty() {
  72. return size() == 0;
  73. }
  74. /**
  75. * Returns <tt>true</tt> if this map maps one or more keys to this value.
  76. * More formally, returns <tt>true</tt> if and only if this map contains
  77. * at least one mapping to a value <tt>v</tt> such that <tt>(value==null ?
  78. * v==null : value.equals(v))</tt>. This operation will probably require
  79. * time linear in the map size for most implementations of map.<p>
  80. *
  81. * This implementation iterates over entrySet() searching for an entry
  82. * with the specified value. If such an entry is found, <tt>true</tt> is
  83. * returned. If the iteration terminates without finding such an entry,
  84. * <tt>false</tt> is returned. Note that this implementation requires
  85. * linear time in the size of the map.
  86. *
  87. * @param value value whose presence in this map is to be tested.
  88. *
  89. * @return <tt>true</tt> if this map maps one or more keys to this value.
  90. */
  91. public boolean containsValue(Object value) {
  92. Iterator i = entrySet().iterator();
  93. if (value==null) {
  94. while (i.hasNext()) {
  95. Entry e = (Entry) i.next();
  96. if (e.getValue()==null)
  97. return true;
  98. }
  99. } else {
  100. while (i.hasNext()) {
  101. Entry e = (Entry) i.next();
  102. if (value.equals(e.getValue()))
  103. return true;
  104. }
  105. }
  106. return false;
  107. }
  108. /**
  109. * Returns <tt>true</tt> if this map contains a mapping for the specified
  110. * key. <p>
  111. *
  112. * This implementation iterates over <tt>entrySet()</tt> searching for an
  113. * entry with the specified key. If such an entry is found, <tt>true</tt>
  114. * is returned. If the iteration terminates without finding such an
  115. * entry, <tt>false</tt> is returned. Note that this implementation
  116. * requires linear time in the size of the map; many implementations will
  117. * override this method.
  118. *
  119. * @param key key whose presence in this map is to be tested.
  120. * @return <tt>true</tt> if this map contains a mapping for the specified
  121. * key.
  122. *
  123. * @throws NullPointerException key is <tt>null</tt> and this map does not
  124. * not permit <tt>null</tt> keys.
  125. */
  126. public boolean containsKey(Object key) {
  127. Iterator i = entrySet().iterator();
  128. if (key==null) {
  129. while (i.hasNext()) {
  130. Entry e = (Entry) i.next();
  131. if (e.getKey()==null)
  132. return true;
  133. }
  134. } else {
  135. while (i.hasNext()) {
  136. Entry e = (Entry) i.next();
  137. if (key.equals(e.getKey()))
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. /**
  144. * Returns the value to which this map maps the specified key. Returns
  145. * <tt>null</tt> if the map contains no mapping for this key. A return
  146. * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
  147. * map contains no mapping for the key; it's also possible that the map
  148. * explicitly maps the key to <tt>null</tt>. The containsKey operation
  149. * may be used to distinguish these two cases. <p>
  150. *
  151. * This implementation iterates over <tt>entrySet()</tt> searching for an
  152. * entry with the specified key. If such an entry is found, the entry's
  153. * value is returned. If the iteration terminates without finding such an
  154. * entry, <tt>null</tt> is returned. Note that this implementation
  155. * requires linear time in the size of the map; many implementations will
  156. * override this method.
  157. *
  158. * @param key key whose associated value is to be returned.
  159. * @return the value to which this map maps the specified key.
  160. *
  161. * @throws NullPointerException if the key is <tt>null</tt> and this map
  162. * does not not permit <tt>null</tt> keys.
  163. *
  164. * @see #containsKey(Object)
  165. */
  166. public Object get(Object key) {
  167. Iterator i = entrySet().iterator();
  168. if (key==null) {
  169. while (i.hasNext()) {
  170. Entry e = (Entry) i.next();
  171. if (e.getKey()==null)
  172. return e.getValue();
  173. }
  174. } else {
  175. while (i.hasNext()) {
  176. Entry e = (Entry) i.next();
  177. if (key.equals(e.getKey()))
  178. return e.getValue();
  179. }
  180. }
  181. return null;
  182. }
  183. // Modification Operations
  184. /**
  185. * Associates the specified value with the specified key in this map
  186. * (optional operation). If the map previously contained a mapping for
  187. * this key, the old value is replaced.<p>
  188. *
  189. * This implementation always throws an
  190. * <tt>UnsupportedOperationException</tt>.
  191. *
  192. * @param key key with which the specified value is to be associated.
  193. * @param value value to be associated with the specified key.
  194. *
  195. * @return previous value associated with specified key, or <tt>null</tt>
  196. * if there was no mapping for key. (A <tt>null</tt> return can
  197. * also indicate that the map previously associated <tt>null</tt>
  198. * with the specified key, if the implementation supports
  199. * <tt>null</tt> values.)
  200. *
  201. * @throws UnsupportedOperationException if the <tt>put</tt> operation is
  202. * not supported by this map.
  203. *
  204. * @throws ClassCastException if the class of the specified key or value
  205. * prevents it from being stored in this map.
  206. *
  207. * @throws IllegalArgumentException if some aspect of this key or value *
  208. * prevents it from being stored in this map.
  209. *
  210. * @throws NullPointerException this map does not permit <tt>null</tt>
  211. * keys or values, and the specified key or value is
  212. * <tt>null</tt>.
  213. */
  214. public Object put(Object key, Object value) {
  215. throw new UnsupportedOperationException();
  216. }
  217. /**
  218. * Removes the mapping for this key from this map if present (optional
  219. * operation). <p>
  220. *
  221. * This implementation iterates over <tt>entrySet()</tt> searching for an
  222. * entry with the specified key. If such an entry is found, its value is
  223. * obtained with its <tt>getValue</tt> operation, the entry is is removed
  224. * from the Collection (and the backing map) with the iterator's
  225. * <tt>remove</tt> operation, and the saved value is returned. If the
  226. * iteration terminates without finding such an entry, <tt>null</tt> is
  227. * returned. Note that this implementation requires linear time in the
  228. * size of the map; many implementations will override this method.<p>
  229. *
  230. * Note that this implementation throws an
  231. * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt> iterator
  232. * does not support the <tt>remove</tt> method and this map contains a
  233. * mapping for the specified key.
  234. *
  235. * @param key key whose mapping is to be removed from the map.
  236. * @return previous value associated with specified key, or <tt>null</tt>
  237. * if there was no entry for key. (A <tt>null</tt> return can
  238. * also indicate that the map previously associated <tt>null</tt>
  239. * with the specified key, if the implementation supports
  240. * <tt>null</tt> values.)
  241. * @throws UnsupportedOperationException if the <tt>remove</tt> operation
  242. * is not supported by this map.
  243. */
  244. public Object remove(Object key) {
  245. Iterator i = entrySet().iterator();
  246. Entry correctEntry = null;
  247. if (key==null) {
  248. while (correctEntry==null && i.hasNext()) {
  249. Entry e = (Entry) i.next();
  250. if (e.getKey()==null)
  251. correctEntry = e;
  252. }
  253. } else {
  254. while (correctEntry==null && i.hasNext()) {
  255. Entry e = (Entry) i.next();
  256. if (key.equals(e.getKey()))
  257. correctEntry = e;
  258. }
  259. }
  260. Object oldValue = null;
  261. if (correctEntry !=null) {
  262. oldValue = correctEntry.getValue();
  263. i.remove();
  264. }
  265. return oldValue;
  266. }
  267. // Bulk Operations
  268. /**
  269. * Copies all of the mappings from the specified map to this map
  270. * (optional operation). These mappings will replace any mappings that
  271. * this map had for any of the keys currently in the specified map.<p>
  272. *
  273. * This implementation iterates over the specified map's
  274. * <tt>entrySet()</tt> collection, and calls this map's <tt>put</tt>
  275. * operation once for each entry returned by the iteration.<p>
  276. *
  277. * Note that this implementation throws an
  278. * <tt>UnsupportedOperationException</tt> if this map does not support
  279. * the <tt>put</tt> operation and the specified map is nonempty.
  280. *
  281. * @param t mappings to be stored in this map.
  282. *
  283. * @throws UnsupportedOperationException if the <tt>putAll</tt> operation
  284. * is not supported by this map.
  285. *
  286. * @throws ClassCastException if the class of a key or value in the
  287. * specified map prevents it from being stored in this map.
  288. *
  289. * @throws IllegalArgumentException if some aspect of a key or value in
  290. * the specified map prevents it from being stored in this map.
  291. * @throws NullPointerException the specified map is <tt>null</tt>, or if
  292. * this map does not permit <tt>null</tt> keys or values, and the
  293. * specified map contains <tt>null</tt> keys or values.
  294. */
  295. public void putAll(Map t) {
  296. Iterator i = t.entrySet().iterator();
  297. while (i.hasNext()) {
  298. Entry e = (Entry) i.next();
  299. put(e.getKey(), e.getValue());
  300. }
  301. }
  302. /**
  303. * Removes all mappings from this map (optional operation). <p>
  304. *
  305. * This implementation calls <tt>entrySet().clear()</tt>.
  306. *
  307. * Note that this implementation throws an
  308. * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt>
  309. * does not support the <tt>clear</tt> operation.
  310. *
  311. * @throws UnsupportedOperationException clear is not supported
  312. * by this map.
  313. */
  314. public void clear() {
  315. entrySet().clear();
  316. }
  317. // Views
  318. /**
  319. * Each of these fields are initialized to contain an instance of the
  320. * appropriate view the first time this view is requested. The views are
  321. * stateless, so there's no reason to create more than one of each.
  322. */
  323. transient volatile Set keySet = null;
  324. transient volatile Collection values = null;
  325. /**
  326. * Returns a Set view of the keys contained in this map. The Set is
  327. * backed by the map, so changes to the map are reflected in the Set,
  328. * and vice-versa. (If the map is modified while an iteration over
  329. * the Set is in progress, the results of the iteration are undefined.)
  330. * The Set supports element removal, which removes the corresponding entry
  331. * from the map, via the Iterator.remove, Set.remove, removeAll
  332. * retainAll, and clear operations. It does not support the add or
  333. * addAll operations.<p>
  334. *
  335. * This implementation returns a Set that subclasses
  336. * AbstractSet. The subclass's iterator method returns a "wrapper
  337. * object" over this map's entrySet() iterator. The size method delegates
  338. * to this map's size method and the contains method delegates to this
  339. * map's containsKey method.<p>
  340. *
  341. * The Set is created the first time this method is called,
  342. * and returned in response to all subsequent calls. No synchronization
  343. * is performed, so there is a slight chance that multiple calls to this
  344. * method will not all return the same Set.
  345. *
  346. * @return a Set view of the keys contained in this map.
  347. */
  348. public Set keySet() {
  349. if (keySet == null) {
  350. keySet = new AbstractSet() {
  351. public Iterator iterator() {
  352. return new Iterator() {
  353. private Iterator i = entrySet().iterator();
  354. public boolean hasNext() {
  355. return i.hasNext();
  356. }
  357. public Object next() {
  358. return ((Entry)i.next()).getKey();
  359. }
  360. public void remove() {
  361. i.remove();
  362. }
  363. };
  364. }
  365. public int size() {
  366. return AbstractMap.this.size();
  367. }
  368. public boolean contains(Object k) {
  369. return AbstractMap.this.containsKey(k);
  370. }
  371. };
  372. }
  373. return keySet;
  374. }
  375. /**
  376. * Returns a collection view of the values contained in this map. The
  377. * collection is backed by the map, so changes to the map are reflected in
  378. * the collection, and vice-versa. (If the map is modified while an
  379. * iteration over the collection is in progress, the results of the
  380. * iteration are undefined.) The collection supports element removal,
  381. * which removes the corresponding entry from the map, via the
  382. * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
  383. * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations.
  384. * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.<p>
  385. *
  386. * This implementation returns a collection that subclasses abstract
  387. * collection. The subclass's iterator method returns a "wrapper object"
  388. * over this map's <tt>entrySet()</tt> iterator. The size method
  389. * delegates to this map's size method and the contains method delegates
  390. * to this map's containsValue method.<p>
  391. *
  392. * The collection is created the first time this method is called, and
  393. * returned in response to all subsequent calls. No synchronization is
  394. * performed, so there is a slight chance that multiple calls to this
  395. * method will not all return the same Collection.
  396. *
  397. * @return a collection view of the values contained in this map.
  398. */
  399. public Collection values() {
  400. if (values == null) {
  401. values = new AbstractCollection() {
  402. public Iterator iterator() {
  403. return new Iterator() {
  404. private Iterator i = entrySet().iterator();
  405. public boolean hasNext() {
  406. return i.hasNext();
  407. }
  408. public Object next() {
  409. return ((Entry)i.next()).getValue();
  410. }
  411. public void remove() {
  412. i.remove();
  413. }
  414. };
  415. }
  416. public int size() {
  417. return AbstractMap.this.size();
  418. }
  419. public boolean contains(Object v) {
  420. return AbstractMap.this.containsValue(v);
  421. }
  422. };
  423. }
  424. return values;
  425. }
  426. /**
  427. * Returns a set view of the mappings contained in this map. Each element
  428. * in this set is a Map.Entry. The set is backed by the map, so changes
  429. * to the map are reflected in the set, and vice-versa. (If the map is
  430. * modified while an iteration over the set is in progress, the results of
  431. * the iteration are undefined.) The set supports element removal, which
  432. * removes the corresponding entry from the map, via the
  433. * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>,
  434. * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support
  435. * the <tt>add</tt> or <tt>addAll</tt> operations.
  436. *
  437. * @return a set view of the mappings contained in this map.
  438. */
  439. public abstract Set entrySet();
  440. // Comparison and hashing
  441. /**
  442. * Compares the specified object with this map for equality. Returns
  443. * <tt>true</tt> if the given object is also a map and the two maps
  444. * represent the same mappings. More formally, two maps <tt>t1</tt> and
  445. * <tt>t2</tt> represent the same mappings if
  446. * <tt>t1.keySet().equals(t2.keySet())</tt> and for every key <tt>k</tt>
  447. * in <tt>t1.keySet()</tt>, <tt> (t1.get(k)==null ? t2.get(k)==null :
  448. * t1.get(k).equals(t2.get(k))) </tt>. This ensures that the
  449. * <tt>equals</tt> method works properly across different implementations
  450. * of the map interface.<p>
  451. *
  452. * This implementation first checks if the specified object is this map;
  453. * if so it returns <tt>true</tt>. Then, it checks if the specified
  454. * object is a map whose size is identical to the size of this set; if
  455. * not, it it returns <tt>false</tt>. If so, it iterates over this map's
  456. * <tt>entrySet</tt> collection, and checks that the specified map
  457. * contains each mapping that this map contains. If the specified map
  458. * fails to contain such a mapping, <tt>false</tt> is returned. If the
  459. * iteration completes, <tt>true</tt> is returned.
  460. *
  461. * @param o object to be compared for equality with this map.
  462. * @return <tt>true</tt> if the specified object is equal to this map.
  463. */
  464. public boolean equals(Object o) {
  465. if (o == this)
  466. return true;
  467. if (!(o instanceof Map))
  468. return false;
  469. Map t = (Map) o;
  470. if (t.size() != size())
  471. return false;
  472. try {
  473. Iterator i = entrySet().iterator();
  474. while (i.hasNext()) {
  475. Entry e = (Entry) i.next();
  476. Object key = e.getKey();
  477. Object value = e.getValue();
  478. if (value == null) {
  479. if (!(t.get(key)==null && t.containsKey(key)))
  480. return false;
  481. } else {
  482. if (!value.equals(t.get(key)))
  483. return false;
  484. }
  485. }
  486. } catch(ClassCastException unused) {
  487. return false;
  488. } catch(NullPointerException unused) {
  489. return false;
  490. }
  491. return true;
  492. }
  493. /**
  494. * Returns the hash code value for this map. The hash code of a map is
  495. * defined to be the sum of the hash codes of each entry in the map's
  496. * <tt>entrySet()</tt> view. This ensures that <tt>t1.equals(t2)</tt>
  497. * implies that <tt>t1.hashCode()==t2.hashCode()</tt> for any two maps
  498. * <tt>t1</tt> and <tt>t2</tt>, as required by the general contract of
  499. * Object.hashCode.<p>
  500. *
  501. * This implementation iterates over <tt>entrySet()</tt>, calling
  502. * <tt>hashCode</tt> on each element (entry) in the Collection, and adding
  503. * up the results.
  504. *
  505. * @return the hash code value for this map.
  506. * @see Map.Entry#hashCode()
  507. * @see Object#hashCode()
  508. * @see Object#equals(Object)
  509. * @see Set#equals(Object)
  510. */
  511. public int hashCode() {
  512. int h = 0;
  513. Iterator i = entrySet().iterator();
  514. while (i.hasNext())
  515. h += i.next().hashCode();
  516. return h;
  517. }
  518. /**
  519. * Returns a string representation of this map. The string representation
  520. * consists of a list of key-value mappings in the order returned by the
  521. * map's <tt>entrySet</tt> view's iterator, enclosed in braces
  522. * (<tt>"{}"</tt>). Adjacent mappings are separated by the characters
  523. * <tt>", "</tt> (comma and space). Each key-value mapping is rendered as
  524. * the key followed by an equals sign (<tt>"="</tt>) followed by the
  525. * associated value. Keys and values are converted to strings as by
  526. * <tt>String.valueOf(Object)</tt>.<p>
  527. *
  528. * This implementation creates an empty string buffer, appends a left
  529. * brace, and iterates over the map's <tt>entrySet</tt> view, appending
  530. * the string representation of each <tt>map.entry</tt> in turn. After
  531. * appending each entry except the last, the string <tt>", "</tt> is
  532. * appended. Finally a right brace is appended. A string is obtained
  533. * from the stringbuffer, and returned.
  534. *
  535. * @return a String representation of this map.
  536. */
  537. public String toString() {
  538. StringBuffer buf = new StringBuffer();
  539. buf.append("{");
  540. Iterator i = entrySet().iterator();
  541. boolean hasNext = i.hasNext();
  542. while (hasNext) {
  543. Entry e = (Entry) (i.next());
  544. Object key = e.getKey();
  545. Object value = e.getValue();
  546. buf.append((key == this ? "(this Map)" : key) + "=" +
  547. (value == this ? "(this Map)": value));
  548. hasNext = i.hasNext();
  549. if (hasNext)
  550. buf.append(", ");
  551. }
  552. buf.append("}");
  553. return buf.toString();
  554. }
  555. /**
  556. * Returns a shallow copy of this <tt>AbstractMap</tt> instance: the keys
  557. * and values themselves are not cloned.
  558. *
  559. * @return a shallow copy of this map.
  560. */
  561. protected Object clone() throws CloneNotSupportedException {
  562. AbstractMap result = (AbstractMap)super.clone();
  563. result.keySet = null;
  564. result.values = null;
  565. return result;
  566. }
  567. /**
  568. * This should be made public as soon as possible. It greately simplifies
  569. * the task of implementing Map.
  570. */
  571. static class SimpleEntry implements Entry {
  572. Object key;
  573. Object value;
  574. public SimpleEntry(Object key, Object value) {
  575. this.key = key;
  576. this.value = value;
  577. }
  578. public SimpleEntry(Map.Entry e) {
  579. this.key = e.getKey();
  580. this.value = e.getValue();
  581. }
  582. public Object getKey() {
  583. return key;
  584. }
  585. public Object getValue() {
  586. return value;
  587. }
  588. public Object setValue(Object value) {
  589. Object oldValue = this.value;
  590. this.value = value;
  591. return oldValue;
  592. }
  593. public boolean equals(Object o) {
  594. if (!(o instanceof Map.Entry))
  595. return false;
  596. Map.Entry e = (Map.Entry)o;
  597. return eq(key, e.getKey()) && eq(value, e.getValue());
  598. }
  599. public int hashCode() {
  600. Object v;
  601. return ((key == null) ? 0 : key.hashCode()) ^
  602. ((value == null) ? 0 : value.hashCode());
  603. }
  604. public String toString() {
  605. return key + "=" + value;
  606. }
  607. private static boolean eq(Object o1, Object o2) {
  608. return (o1 == null ? o2 == null : o1.equals(o2));
  609. }
  610. }
  611. }