ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/AbstractMap.java
Revision: 1.13
Committed: Mon Jun 20 18:02:22 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.12: +5 -4 lines
Log Message:
cosmetic changes

File Contents

# Content
1 /*
2 * %W% %E%
3 *
4 * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
5 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6 */
7
8 package java.util;
9 import java.util.*; // for javadoc (till 6280605 is fixed)
10 import java.util.Map.Entry;
11
12 /**
13 * This class provides a skeletal implementation of the <tt>Map</tt>
14 * interface, to minimize the effort required to implement this interface.
15 *
16 * <p>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.
22 *
23 * <p>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.
28 *
29 * <p>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.
32 *
33 * <p>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 * <p>This class is a member of the
38 * <a href="{@docRoot}/../guide/collections/index.html">
39 * Java Collections Framework</a>.
40 *
41 * @param <K> the type of keys maintained by this map
42 * @param <V> the type of mapped values
43 *
44 * @author Josh Bloch
45 * @author Neal Gafter
46 * @version %I%, %G%
47 * @see Map
48 * @see Collection
49 * @since 1.2
50 */
51
52 public abstract class AbstractMap<K,V> implements Map<K,V> {
53 /**
54 * Sole constructor. (For invocation by subclass constructors, typically
55 * implicit.)
56 */
57 protected AbstractMap() {
58 }
59
60 // Query Operations
61
62 /**
63 * {@inheritDoc}
64 *
65 * <p>This implementation returns <tt>entrySet().size()</tt>.
66 */
67 public int size() {
68 return entrySet().size();
69 }
70
71 /**
72 * {@inheritDoc}
73 *
74 * <p>This implementation returns <tt>size() == 0</tt>.
75 */
76 public boolean isEmpty() {
77 return size() == 0;
78 }
79
80 /**
81 * {@inheritDoc}
82 *
83 * <p>This implementation iterates over <tt>entrySet()</tt> searching
84 * for an entry with the specified value. If such an entry is found,
85 * <tt>true</tt> is returned. If the iteration terminates without
86 * finding such an entry, <tt>false</tt> is returned. Note that this
87 * implementation requires linear time in the size of the map.
88 *
89 * @throws ClassCastException {@inheritDoc}
90 * @throws NullPointerException {@inheritDoc}
91 */
92 public boolean containsValue(Object value) {
93 Iterator<Entry<K,V>> i = entrySet().iterator();
94 if (value==null) {
95 while (i.hasNext()) {
96 Entry<K,V> e = i.next();
97 if (e.getValue()==null)
98 return true;
99 }
100 } else {
101 while (i.hasNext()) {
102 Entry<K,V> e = i.next();
103 if (value.equals(e.getValue()))
104 return true;
105 }
106 }
107 return false;
108 }
109
110 /**
111 * {@inheritDoc}
112 *
113 * <p>This implementation iterates over <tt>entrySet()</tt> searching
114 * for an entry with the specified key. If such an entry is found,
115 * <tt>true</tt> is returned. If the iteration terminates without
116 * finding such an entry, <tt>false</tt> is returned. Note that this
117 * implementation requires linear time in the size of the map; many
118 * implementations will override this method.
119 *
120 * @throws ClassCastException {@inheritDoc}
121 * @throws NullPointerException {@inheritDoc}
122 */
123 public boolean containsKey(Object key) {
124 Iterator<Map.Entry<K,V>> i = entrySet().iterator();
125 if (key==null) {
126 while (i.hasNext()) {
127 Entry<K,V> e = i.next();
128 if (e.getKey()==null)
129 return true;
130 }
131 } else {
132 while (i.hasNext()) {
133 Entry<K,V> e = i.next();
134 if (key.equals(e.getKey()))
135 return true;
136 }
137 }
138 return false;
139 }
140
141 /**
142 * {@inheritDoc}
143 *
144 * <p>This implementation iterates over <tt>entrySet()</tt> searching
145 * for an entry with the specified key. If such an entry is found,
146 * the entry's value is returned. If the iteration terminates without
147 * finding such an entry, <tt>null</tt> is returned. Note that this
148 * implementation requires linear time in the size of the map; many
149 * implementations will override this method.
150 *
151 * @throws ClassCastException {@inheritDoc}
152 * @throws NullPointerException {@inheritDoc}
153 */
154 public V get(Object key) {
155 Iterator<Entry<K,V>> i = entrySet().iterator();
156 if (key==null) {
157 while (i.hasNext()) {
158 Entry<K,V> e = i.next();
159 if (e.getKey()==null)
160 return e.getValue();
161 }
162 } else {
163 while (i.hasNext()) {
164 Entry<K,V> e = i.next();
165 if (key.equals(e.getKey()))
166 return e.getValue();
167 }
168 }
169 return null;
170 }
171
172
173 // Modification Operations
174
175 /**
176 * {@inheritDoc}
177 *
178 * <p>This implementation always throws an
179 * <tt>UnsupportedOperationException</tt>.
180 *
181 * @throws UnsupportedOperationException {@inheritDoc}
182 * @throws ClassCastException {@inheritDoc}
183 * @throws NullPointerException {@inheritDoc}
184 * @throws IllegalArgumentException {@inheritDoc}
185 */
186 public V put(K key, V value) {
187 throw new UnsupportedOperationException();
188 }
189
190 /**
191 * {@inheritDoc}
192 *
193 * <p>This implementation iterates over <tt>entrySet()</tt> searching for an
194 * entry with the specified key. If such an entry is found, its value is
195 * obtained with its <tt>getValue</tt> operation, the entry is removed
196 * from the collection (and the backing map) with the iterator's
197 * <tt>remove</tt> operation, and the saved value is returned. If the
198 * iteration terminates without finding such an entry, <tt>null</tt> is
199 * returned. Note that this implementation requires linear time in the
200 * size of the map; many implementations will override this method.
201 *
202 * <p>Note that this implementation throws an
203 * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt>
204 * iterator does not support the <tt>remove</tt> method and this map
205 * contains a mapping for the specified key.
206 *
207 * @throws UnsupportedOperationException {@inheritDoc}
208 * @throws ClassCastException {@inheritDoc}
209 * @throws NullPointerException {@inheritDoc}
210 */
211 public V remove(Object key) {
212 Iterator<Entry<K,V>> i = entrySet().iterator();
213 Entry<K,V> correctEntry = null;
214 if (key==null) {
215 while (correctEntry==null && i.hasNext()) {
216 Entry<K,V> e = i.next();
217 if (e.getKey()==null)
218 correctEntry = e;
219 }
220 } else {
221 while (correctEntry==null && i.hasNext()) {
222 Entry<K,V> e = i.next();
223 if (key.equals(e.getKey()))
224 correctEntry = e;
225 }
226 }
227
228 V oldValue = null;
229 if (correctEntry !=null) {
230 oldValue = correctEntry.getValue();
231 i.remove();
232 }
233 return oldValue;
234 }
235
236
237 // Bulk Operations
238
239 /**
240 * {@inheritDoc}
241 *
242 * <p>This implementation iterates over the specified map's
243 * <tt>entrySet()</tt> collection, and calls this map's <tt>put</tt>
244 * operation once for each entry returned by the iteration.
245 *
246 * <p>Note that this implementation throws an
247 * <tt>UnsupportedOperationException</tt> if this map does not support
248 * the <tt>put</tt> operation and the specified map is nonempty.
249 *
250 * @throws UnsupportedOperationException {@inheritDoc}
251 * @throws ClassCastException {@inheritDoc}
252 * @throws NullPointerException {@inheritDoc}
253 * @throws IllegalArgumentException {@inheritDoc}
254 */
255 public void putAll(Map<? extends K, ? extends V> m) {
256 Iterator<? extends Entry<? extends K, ? extends V>> i = m.entrySet().iterator();
257 while (i.hasNext()) {
258 Entry<? extends K, ? extends V> e = i.next();
259 put(e.getKey(), e.getValue());
260 }
261 }
262
263 /**
264 * {@inheritDoc}
265 *
266 * <p>This implementation calls <tt>entrySet().clear()</tt>.
267 *
268 * <p>Note that this implementation throws an
269 * <tt>UnsupportedOperationException</tt> if the <tt>entrySet</tt>
270 * does not support the <tt>clear</tt> operation.
271 *
272 * @throws UnsupportedOperationException {@inheritDoc}
273 */
274 public void clear() {
275 entrySet().clear();
276 }
277
278
279 // Views
280
281 /**
282 * Each of these fields are initialized to contain an instance of the
283 * appropriate view the first time this view is requested. The views are
284 * stateless, so there's no reason to create more than one of each.
285 */
286 transient volatile Set<K> keySet = null;
287 transient volatile Collection<V> values = null;
288
289 /**
290 * {@inheritDoc}
291 *
292 * <p>This implementation returns a set that subclasses {@link AbstractSet}.
293 * The subclass's iterator method returns a "wrapper object" over this
294 * map's <tt>entrySet()</tt> iterator. The <tt>size</tt> method
295 * delegates to this map's <tt>size</tt> method and the
296 * <tt>contains</tt> method delegates to this map's
297 * <tt>containsKey</tt> method.
298 *
299 * <p>The set is created the first time this method is called,
300 * and returned in response to all subsequent calls. No synchronization
301 * is performed, so there is a slight chance that multiple calls to this
302 * method will not all return the same set.
303 */
304 public Set<K> keySet() {
305 if (keySet == null) {
306 keySet = new AbstractSet<K>() {
307 public Iterator<K> iterator() {
308 return new Iterator<K>() {
309 private Iterator<Entry<K,V>> i = entrySet().iterator();
310
311 public boolean hasNext() {
312 return i.hasNext();
313 }
314
315 public K next() {
316 return i.next().getKey();
317 }
318
319 public void remove() {
320 i.remove();
321 }
322 };
323 }
324
325 public int size() {
326 return AbstractMap.this.size();
327 }
328
329 public boolean contains(Object k) {
330 return AbstractMap.this.containsKey(k);
331 }
332 };
333 }
334 return keySet;
335 }
336
337 /**
338 * {@inheritDoc}
339 *
340 * <p>This implementation returns a collection that subclasses {@link
341 * AbstractCollection}. The subclass's iterator method returns a
342 * "wrapper object" over this map's <tt>entrySet()</tt> iterator.
343 * The <tt>size</tt> method delegates to this map's <tt>size</tt>
344 * method and the <tt>contains</tt> method delegates to this map's
345 * <tt>containsValue</tt> method.
346 *
347 * <p>The collection is created the first time this method is called, and
348 * returned in response to all subsequent calls. No synchronization is
349 * performed, so there is a slight chance that multiple calls to this
350 * method will not all return the same collection.
351 */
352 public Collection<V> values() {
353 if (values == null) {
354 values = new AbstractCollection<V>() {
355 public Iterator<V> iterator() {
356 return new Iterator<V>() {
357 private Iterator<Entry<K,V>> i = entrySet().iterator();
358
359 public boolean hasNext() {
360 return i.hasNext();
361 }
362
363 public V next() {
364 return i.next().getValue();
365 }
366
367 public void remove() {
368 i.remove();
369 }
370 };
371 }
372
373 public int size() {
374 return AbstractMap.this.size();
375 }
376
377 public boolean contains(Object v) {
378 return AbstractMap.this.containsValue(v);
379 }
380 };
381 }
382 return values;
383 }
384
385 public abstract Set<Entry<K,V>> entrySet();
386
387
388 // Comparison and hashing
389
390 /**
391 * {@inheritDoc}
392 *
393 * <p>This implementation first checks if the specified object is this map;
394 * if so it returns <tt>true</tt>. Then, it checks if the specified
395 * object is a map whose size is identical to the size of this map; if
396 * not, it returns <tt>false</tt>. If so, it iterates over this map's
397 * <tt>entrySet</tt> collection, and checks that the specified map
398 * contains each mapping that this map contains. If the specified map
399 * fails to contain such a mapping, <tt>false</tt> is returned. If the
400 * iteration completes, <tt>true</tt> is returned.
401 */
402 public boolean equals(Object o) {
403 if (o == this)
404 return true;
405
406 if (!(o instanceof Map))
407 return false;
408 Map<K,V> m = (Map<K,V>) o;
409 if (m.size() != size())
410 return false;
411
412 try {
413 Iterator<Entry<K,V>> i = entrySet().iterator();
414 while (i.hasNext()) {
415 Entry<K,V> e = i.next();
416 K key = e.getKey();
417 V value = e.getValue();
418 if (value == null) {
419 if (!(m.get(key)==null && m.containsKey(key)))
420 return false;
421 } else {
422 if (!value.equals(m.get(key)))
423 return false;
424 }
425 }
426 } catch (ClassCastException unused) {
427 return false;
428 } catch (NullPointerException unused) {
429 return false;
430 }
431
432 return true;
433 }
434
435 /**
436 * {@inheritDoc}
437 *
438 * <p>This implementation iterates over <tt>entrySet()</tt>, calling
439 * <tt>hashCode()</tt> on each element (entry) in the set, and
440 * adding up the results.
441 *
442 * @see Map.Entry#hashCode()
443 * @see Object#hashCode()
444 * @see Object#equals(Object)
445 * @see Set#equals(Object)
446 */
447 public int hashCode() {
448 int h = 0;
449 Iterator<Entry<K,V>> i = entrySet().iterator();
450 while (i.hasNext())
451 h += i.next().hashCode();
452 return h;
453 }
454
455 /**
456 * Returns a string representation of this map. The string representation
457 * consists of a list of key-value mappings in the order returned by the
458 * map's <tt>entrySet</tt> view's iterator, enclosed in braces
459 * (<tt>"{}"</tt>). Adjacent mappings are separated by the characters
460 * <tt>", "</tt> (comma and space). Each key-value mapping is rendered as
461 * the key followed by an equals sign (<tt>"="</tt>) followed by the
462 * associated value. Keys and values are converted to strings as by
463 * <tt>String.valueOf(Object)</tt>.<p>
464 *
465 * This implementation creates an empty string buffer, appends a left
466 * brace, and iterates over the map's <tt>entrySet</tt> view, appending
467 * the string representation of each <tt>map.entry</tt> in turn. After
468 * appending each entry except the last, the string <tt>", "</tt> is
469 * appended. Finally a right brace is appended. A string is obtained
470 * from the stringbuffer, and returned.
471 *
472 * @return a String representation of this map
473 */
474 public String toString() {
475 StringBuilder sb = new StringBuilder();
476 sb.append("{");
477
478 Iterator<Entry<K,V>> i = entrySet().iterator();
479 boolean hasNext = i.hasNext();
480 while (hasNext) {
481 Entry<K,V> e = i.next();
482 K key = e.getKey();
483 V value = e.getValue();
484 if (key == this)
485 sb.append("(this Map)");
486 else
487 sb.append(key);
488 sb.append("=");
489 if (value == this)
490 sb.append("(this Map)");
491 else
492 sb.append(value);
493 hasNext = i.hasNext();
494 if (hasNext)
495 sb.append(", ");
496 }
497
498 sb.append("}");
499 return sb.toString();
500 }
501
502 /**
503 * Returns a shallow copy of this <tt>AbstractMap</tt> instance: the keys
504 * and values themselves are not cloned.
505 *
506 * @return a shallow copy of this map
507 */
508 protected Object clone() throws CloneNotSupportedException {
509 AbstractMap<K,V> result = (AbstractMap<K,V>)super.clone();
510 result.keySet = null;
511 result.values = null;
512 return result;
513 }
514
515 /**
516 * Utility method for SimpleEntry and SimpleImmutableEntry.
517 * Test for equality, checking for nulls.
518 */
519 private static boolean eq(Object o1, Object o2) {
520 return (o1 == null ? o2 == null : o1.equals(o2));
521 }
522
523 // Implementation Note: SimpleEntry and SimpleImmutableEntry
524 // are distinct unrelated classes, even though they share
525 // some code. Since you can't add or subtract final-ness
526 // of a field in a subclass, they can't share representations,
527 // and the amount of duplicated code is too small to warrant
528 // exposing a common abstract class.
529
530
531 /**
532 * An Entry maintaining a key and a value. The value may be
533 * changed using the <tt>setValue</tt> method. This class
534 * facilitates the process of building custom map
535 * implementations. For example, it may be convenient to return
536 * arrays of <tt>SimpleEntry</tt> instances in method
537 * <tt>Map.entrySet().toArray</tt>
538 */
539 public static class SimpleEntry<K,V> implements Entry<K,V> {
540 private final K key;
541 private V value;
542
543 /**
544 * Creates an entry representing a mapping from the specified
545 * key to the specified value.
546 *
547 * @param key the key represented by this entry
548 * @param value the value represented by this entry
549 */
550 public SimpleEntry(K key, V value) {
551 this.key = key;
552 this.value = value;
553 }
554
555 /**
556 * Creates an entry representing the same mapping as the
557 * specified entry.
558 *
559 * @param entry the entry to copy
560 */
561 public SimpleEntry(Entry<? extends K, ? extends V> entry) {
562 this.key = entry.getKey();
563 this.value = entry.getValue();
564 }
565
566 /**
567 * Returns the key corresponding to this entry.
568 *
569 * @return the key corresponding to this entry
570 */
571 public K getKey() {
572 return key;
573 }
574
575 /**
576 * Returns the value corresponding to this entry.
577 *
578 * @return the value corresponding to this entry
579 */
580 public V getValue() {
581 return value;
582 }
583
584 /**
585 * Replaces the value corresponding to this entry with the specified
586 * value.
587 *
588 * @param value new value to be stored in this entry
589 * @return the old value corresponding to the entry
590 */
591 public V setValue(V value) {
592 V oldValue = this.value;
593 this.value = value;
594 return oldValue;
595 }
596
597 public boolean equals(Object o) {
598 if (!(o instanceof Map.Entry))
599 return false;
600 Map.Entry e = (Map.Entry)o;
601 return eq(key, e.getKey()) && eq(value, e.getValue());
602 }
603
604 public int hashCode() {
605 return ((key == null) ? 0 : key.hashCode()) ^
606 ((value == null) ? 0 : value.hashCode());
607 }
608
609 /**
610 * Returns a String representation of this map entry. This
611 * implementation returns the string representation of this
612 * entry's key followed by the equals character ("<tt>=</tt>")
613 * followed by the string representation of this entry's value.
614 *
615 * @return a String representation of this map entry
616 */
617 public String toString() {
618 return key + "=" + value;
619 }
620
621 }
622
623 /**
624 * An Entry maintaining an immutable key and value, This class
625 * does not support method <tt>setValue</tt>. This class may be
626 * convenient in methods that return thread-safe snapshots of
627 * key-value mappings.
628 */
629 public static class SimpleImmutableEntry<K,V> implements Entry<K,V> {
630 private final K key;
631 private final V value;
632
633 /**
634 * Creates an entry representing a mapping from the specified
635 * key to the specified value.
636 *
637 * @param key the key represented by this entry
638 * @param value the value represented by this entry
639 */
640 public SimpleImmutableEntry(K key, V value) {
641 this.key = key;
642 this.value = value;
643 }
644
645 /**
646 * Creates an entry representing the same mapping as the
647 * specified entry.
648 *
649 * @param entry the entry to copy
650 */
651 public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
652 this.key = entry.getKey();
653 this.value = entry.getValue();
654 }
655
656 /**
657 * Returns the key corresponding to this entry.
658 *
659 * @return the key corresponding to this entry
660 */
661 public K getKey() {
662 return key;
663 }
664
665 /**
666 * Returns the value corresponding to this entry.
667 *
668 * @return the value corresponding to this entry
669 */
670 public V getValue() {
671 return value;
672 }
673
674 /**
675 * Replaces the value corresponding to this entry with the specified
676 * value (optional operation). This implementation simply throws
677 * <tt>UnsupportedOperationException</tt>, as this class implements
678 * an <i>immutable</i> map entry.
679 *
680 * @param value new value to be stored in this entry
681 * @return (Does not return)
682 * @throws UnsupportedOperationException always
683 */
684 public V setValue(V value) {
685 throw new UnsupportedOperationException();
686 }
687
688 public boolean equals(Object o) {
689 if (!(o instanceof Map.Entry))
690 return false;
691 Map.Entry e = (Map.Entry)o;
692 return eq(key, e.getKey()) && eq(value, e.getValue());
693 }
694
695 public int hashCode() {
696 return ((key == null) ? 0 : key.hashCode()) ^
697 ((value == null) ? 0 : value.hashCode());
698 }
699
700 /**
701 * Returns a String representation of this map entry. This
702 * implementation returns the string representation of this
703 * entry's key followed by the equals character ("<tt>=</tt>")
704 * followed by the string representation of this entry's value.
705 *
706 * @return a String representation of this map entry
707 */
708 public String toString() {
709 return key + "=" + value;
710 }
711
712 }
713
714 }