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