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