Map.java revision 8b056f0b15bc1e45da8d4c504353b05e681ac013
1/*
2 * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.util;
27
28
29import java.io.Serializable;
30import java.util.function.BiConsumer;
31import java.util.function.BiFunction;
32import java.util.function.Function;
33
34
35/**
36 * An object that maps keys to values.  A map cannot contain duplicate keys;
37 * each key can map to at most one value.
38 *
39 * <p>This interface takes the place of the <tt>Dictionary</tt> class, which
40 * was a totally abstract class rather than an interface.
41 *
42 * <p>The <tt>Map</tt> interface provides three <i>collection views</i>, which
43 * allow a map's contents to be viewed as a set of keys, collection of values,
44 * or set of key-value mappings.  The <i>order</i> of a map is defined as
45 * the order in which the iterators on the map's collection views return their
46 * elements.  Some map implementations, like the <tt>TreeMap</tt> class, make
47 * specific guarantees as to their order; others, like the <tt>HashMap</tt>
48 * class, do not.
49 *
50 * <p>Note: great care must be exercised if mutable objects are used as map
51 * keys.  The behavior of a map is not specified if the value of an object is
52 * changed in a manner that affects <tt>equals</tt> comparisons while the
53 * object is a key in the map.  A special case of this prohibition is that it
54 * is not permissible for a map to contain itself as a key.  While it is
55 * permissible for a map to contain itself as a value, extreme caution is
56 * advised: the <tt>equals</tt> and <tt>hashCode</tt> methods are no longer
57 * well defined on such a map.
58 *
59 * <p>All general-purpose map implementation classes should provide two
60 * "standard" constructors: a void (no arguments) constructor which creates an
61 * empty map, and a constructor with a single argument of type <tt>Map</tt>,
62 * which creates a new map with the same key-value mappings as its argument.
63 * In effect, the latter constructor allows the user to copy any map,
64 * producing an equivalent map of the desired class.  There is no way to
65 * enforce this recommendation (as interfaces cannot contain constructors) but
66 * all of the general-purpose map implementations in the JDK comply.
67 *
68 * <p>The "destructive" methods contained in this interface, that is, the
69 * methods that modify the map on which they operate, are specified to throw
70 * <tt>UnsupportedOperationException</tt> if this map does not support the
71 * operation.  If this is the case, these methods may, but are not required
72 * to, throw an <tt>UnsupportedOperationException</tt> if the invocation would
73 * have no effect on the map.  For example, invoking the {@link #putAll(Map)}
74 * method on an unmodifiable map may, but is not required to, throw the
75 * exception if the map whose mappings are to be "superimposed" is empty.
76 *
77 * <p>Some map implementations have restrictions on the keys and values they
78 * may contain.  For example, some implementations prohibit null keys and
79 * values, and some have restrictions on the types of their keys.  Attempting
80 * to insert an ineligible key or value throws an unchecked exception,
81 * typically <tt>NullPointerException</tt> or <tt>ClassCastException</tt>.
82 * Attempting to query the presence of an ineligible key or value may throw an
83 * exception, or it may simply return false; some implementations will exhibit
84 * the former behavior and some will exhibit the latter.  More generally,
85 * attempting an operation on an ineligible key or value whose completion
86 * would not result in the insertion of an ineligible element into the map may
87 * throw an exception or it may succeed, at the option of the implementation.
88 * Such exceptions are marked as "optional" in the specification for this
89 * interface.
90 *
91 * <p>This interface is a member of the
92 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
93 * Java Collections Framework</a>.
94 *
95 * <p>Many methods in Collections Framework interfaces are defined
96 * in terms of the {@link Object#equals(Object) equals} method.  For
97 * example, the specification for the {@link #containsKey(Object)
98 * containsKey(Object key)} method says: "returns <tt>true</tt> if and
99 * only if this map contains a mapping for a key <tt>k</tt> such that
100 * <tt>(key==null ? k==null : key.equals(k))</tt>." This specification should
101 * <i>not</i> be construed to imply that invoking <tt>Map.containsKey</tt>
102 * with a non-null argument <tt>key</tt> will cause <tt>key.equals(k)</tt> to
103 * be invoked for any key <tt>k</tt>.  Implementations are free to
104 * implement optimizations whereby the <tt>equals</tt> invocation is avoided,
105 * for example, by first comparing the hash codes of the two keys.  (The
106 * {@link Object#hashCode()} specification guarantees that two objects with
107 * unequal hash codes cannot be equal.)  More generally, implementations of
108 * the various Collections Framework interfaces are free to take advantage of
109 * the specified behavior of underlying {@link Object} methods wherever the
110 * implementor deems it appropriate.
111 *
112 * @param <K> the type of keys maintained by this map
113 * @param <V> the type of mapped values
114 *
115 * @author  Josh Bloch
116 * @see HashMap
117 * @see TreeMap
118 * @see Hashtable
119 * @see SortedMap
120 * @see Collection
121 * @see Set
122 * @since 1.2
123 */
124public interface Map<K,V> {
125    // Query Operations
126
127    /**
128     * Returns the number of key-value mappings in this map.  If the
129     * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
130     * <tt>Integer.MAX_VALUE</tt>.
131     *
132     * @return the number of key-value mappings in this map
133     */
134    int size();
135
136    /**
137     * Returns <tt>true</tt> if this map contains no key-value mappings.
138     *
139     * @return <tt>true</tt> if this map contains no key-value mappings
140     */
141    boolean isEmpty();
142
143    /**
144     * Returns <tt>true</tt> if this map contains a mapping for the specified
145     * key.  More formally, returns <tt>true</tt> if and only if
146     * this map contains a mapping for a key <tt>k</tt> such that
147     * <tt>(key==null ? k==null : key.equals(k))</tt>.  (There can be
148     * at most one such mapping.)
149     *
150     * @param key key whose presence in this map is to be tested
151     * @return <tt>true</tt> if this map contains a mapping for the specified
152     *         key
153     * @throws ClassCastException if the key is of an inappropriate type for
154     *         this map
155     * (<a href="Collection.html#optional-restrictions">optional</a>)
156     * @throws NullPointerException if the specified key is null and this map
157     *         does not permit null keys
158     * (<a href="Collection.html#optional-restrictions">optional</a>)
159     */
160    boolean containsKey(Object key);
161
162    /**
163     * Returns <tt>true</tt> if this map maps one or more keys to the
164     * specified value.  More formally, returns <tt>true</tt> if and only if
165     * this map contains at least one mapping to a value <tt>v</tt> such that
166     * <tt>(value==null ? v==null : value.equals(v))</tt>.  This operation
167     * will probably require time linear in the map size for most
168     * implementations of the <tt>Map</tt> interface.
169     *
170     * @param value value whose presence in this map is to be tested
171     * @return <tt>true</tt> if this map maps one or more keys to the
172     *         specified value
173     * @throws ClassCastException if the value is of an inappropriate type for
174     *         this map
175     * (<a href="Collection.html#optional-restrictions">optional</a>)
176     * @throws NullPointerException if the specified value is null and this
177     *         map does not permit null values
178     * (<a href="Collection.html#optional-restrictions">optional</a>)
179     */
180    boolean containsValue(Object value);
181
182    /**
183     * Returns the value to which the specified key is mapped,
184     * or {@code null} if this map contains no mapping for the key.
185     *
186     * <p>More formally, if this map contains a mapping from a key
187     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
188     * key.equals(k))}, then this method returns {@code v}; otherwise
189     * it returns {@code null}.  (There can be at most one such mapping.)
190     *
191     * <p>If this map permits null values, then a return value of
192     * {@code null} does not <i>necessarily</i> indicate that the map
193     * contains no mapping for the key; it's also possible that the map
194     * explicitly maps the key to {@code null}.  The {@link #containsKey
195     * containsKey} operation may be used to distinguish these two cases.
196     *
197     * @param key the key whose associated value is to be returned
198     * @return the value to which the specified key is mapped, or
199     *         {@code null} if this map contains no mapping for the key
200     * @throws ClassCastException if the key is of an inappropriate type for
201     *         this map
202     * (<a href="Collection.html#optional-restrictions">optional</a>)
203     * @throws NullPointerException if the specified key is null and this map
204     *         does not permit null keys
205     * (<a href="Collection.html#optional-restrictions">optional</a>)
206     */
207    V get(Object key);
208
209    // Modification Operations
210
211    /**
212     * Associates the specified value with the specified key in this map
213     * (optional operation).  If the map previously contained a mapping for
214     * the key, the old value is replaced by the specified value.  (A map
215     * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
216     * if {@link #containsKey(Object) m.containsKey(k)} would return
217     * <tt>true</tt>.)
218     *
219     * @param key key with which the specified value is to be associated
220     * @param value value to be associated with the specified key
221     * @return the previous value associated with <tt>key</tt>, or
222     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
223     *         (A <tt>null</tt> return can also indicate that the map
224     *         previously associated <tt>null</tt> with <tt>key</tt>,
225     *         if the implementation supports <tt>null</tt> values.)
226     * @throws UnsupportedOperationException if the <tt>put</tt> operation
227     *         is not supported by this map
228     * @throws ClassCastException if the class of the specified key or value
229     *         prevents it from being stored in this map
230     * @throws NullPointerException if the specified key or value is null
231     *         and this map does not permit null keys or values
232     * @throws IllegalArgumentException if some property of the specified key
233     *         or value prevents it from being stored in this map
234     */
235    V put(K key, V value);
236
237    /**
238     * Removes the mapping for a key from this map if it is present
239     * (optional operation).   More formally, if this map contains a mapping
240     * from key <tt>k</tt> to value <tt>v</tt> such that
241     * <code>(key==null ?  k==null : key.equals(k))</code>, that mapping
242     * is removed.  (The map can contain at most one such mapping.)
243     *
244     * <p>Returns the value to which this map previously associated the key,
245     * or <tt>null</tt> if the map contained no mapping for the key.
246     *
247     * <p>If this map permits null values, then a return value of
248     * <tt>null</tt> does not <i>necessarily</i> indicate that the map
249     * contained no mapping for the key; it's also possible that the map
250     * explicitly mapped the key to <tt>null</tt>.
251     *
252     * <p>The map will not contain a mapping for the specified key once the
253     * call returns.
254     *
255     * @param key key whose mapping is to be removed from the map
256     * @return the previous value associated with <tt>key</tt>, or
257     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
258     * @throws UnsupportedOperationException if the <tt>remove</tt> operation
259     *         is not supported by this map
260     * @throws ClassCastException if the key is of an inappropriate type for
261     *         this map
262     * (<a href="Collection.html#optional-restrictions">optional</a>)
263     * @throws NullPointerException if the specified key is null and this
264     *         map does not permit null keys
265     * (<a href="Collection.html#optional-restrictions">optional</a>)
266     */
267    V remove(Object key);
268
269
270    // Bulk Operations
271
272    /**
273     * Copies all of the mappings from the specified map to this map
274     * (optional operation).  The effect of this call is equivalent to that
275     * of calling {@link #put(Object,Object) put(k, v)} on this map once
276     * for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
277     * specified map.  The behavior of this operation is undefined if the
278     * specified map is modified while the operation is in progress.
279     *
280     * @param m mappings to be stored in this map
281     * @throws UnsupportedOperationException if the <tt>putAll</tt> operation
282     *         is not supported by this map
283     * @throws ClassCastException if the class of a key or value in the
284     *         specified map prevents it from being stored in this map
285     * @throws NullPointerException if the specified map is null, or if
286     *         this map does not permit null keys or values, and the
287     *         specified map contains null keys or values
288     * @throws IllegalArgumentException if some property of a key or value in
289     *         the specified map prevents it from being stored in this map
290     */
291    void putAll(Map<? extends K, ? extends V> m);
292
293    /**
294     * Removes all of the mappings from this map (optional operation).
295     * The map will be empty after this call returns.
296     *
297     * @throws UnsupportedOperationException if the <tt>clear</tt> operation
298     *         is not supported by this map
299     */
300    void clear();
301
302
303    // Views
304
305    /**
306     * Returns a {@link Set} view of the keys contained in this map.
307     * The set is backed by the map, so changes to the map are
308     * reflected in the set, and vice-versa.  If the map is modified
309     * while an iteration over the set is in progress (except through
310     * the iterator's own <tt>remove</tt> operation), the results of
311     * the iteration are undefined.  The set supports element removal,
312     * which removes the corresponding mapping from the map, via the
313     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
314     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
315     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
316     * operations.
317     *
318     * @return a set view of the keys contained in this map
319     */
320    Set<K> keySet();
321
322    /**
323     * Returns a {@link Collection} view of the values contained in this map.
324     * The collection is backed by the map, so changes to the map are
325     * reflected in the collection, and vice-versa.  If the map is
326     * modified while an iteration over the collection is in progress
327     * (except through the iterator's own <tt>remove</tt> operation),
328     * the results of the iteration are undefined.  The collection
329     * supports element removal, which removes the corresponding
330     * mapping from the map, via the <tt>Iterator.remove</tt>,
331     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
332     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
333     * support the <tt>add</tt> or <tt>addAll</tt> operations.
334     *
335     * @return a collection view of the values contained in this map
336     */
337    Collection<V> values();
338
339    /**
340     * Returns a {@link Set} view of the mappings contained in this map.
341     * The set is backed by the map, so changes to the map are
342     * reflected in the set, and vice-versa.  If the map is modified
343     * while an iteration over the set is in progress (except through
344     * the iterator's own <tt>remove</tt> operation, or through the
345     * <tt>setValue</tt> operation on a map entry returned by the
346     * iterator) the results of the iteration are undefined.  The set
347     * supports element removal, which removes the corresponding
348     * mapping from the map, via the <tt>Iterator.remove</tt>,
349     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
350     * <tt>clear</tt> operations.  It does not support the
351     * <tt>add</tt> or <tt>addAll</tt> operations.
352     *
353     * @return a set view of the mappings contained in this map
354     */
355    Set<Map.Entry<K, V>> entrySet();
356
357    /**
358     * A map entry (key-value pair).  The <tt>Map.entrySet</tt> method returns
359     * a collection-view of the map, whose elements are of this class.  The
360     * <i>only</i> way to obtain a reference to a map entry is from the
361     * iterator of this collection-view.  These <tt>Map.Entry</tt> objects are
362     * valid <i>only</i> for the duration of the iteration; more formally,
363     * the behavior of a map entry is undefined if the backing map has been
364     * modified after the entry was returned by the iterator, except through
365     * the <tt>setValue</tt> operation on the map entry.
366     *
367     * @see Map#entrySet()
368     * @since 1.2
369     */
370    interface Entry<K,V> {
371        /**
372         * Returns the key corresponding to this entry.
373         *
374         * @return the key corresponding to this entry
375         * @throws IllegalStateException implementations may, but are not
376         *         required to, throw this exception if the entry has been
377         *         removed from the backing map.
378         */
379        K getKey();
380
381        /**
382         * Returns the value corresponding to this entry.  If the mapping
383         * has been removed from the backing map (by the iterator's
384         * <tt>remove</tt> operation), the results of this call are undefined.
385         *
386         * @return the value corresponding to this entry
387         * @throws IllegalStateException implementations may, but are not
388         *         required to, throw this exception if the entry has been
389         *         removed from the backing map.
390         */
391        V getValue();
392
393        /**
394         * Replaces the value corresponding to this entry with the specified
395         * value (optional operation).  (Writes through to the map.)  The
396         * behavior of this call is undefined if the mapping has already been
397         * removed from the map (by the iterator's <tt>remove</tt> operation).
398         *
399         * @param value new value to be stored in this entry
400         * @return old value corresponding to the entry
401         * @throws UnsupportedOperationException if the <tt>put</tt> operation
402         *         is not supported by the backing map
403         * @throws ClassCastException if the class of the specified value
404         *         prevents it from being stored in the backing map
405         * @throws NullPointerException if the backing map does not permit
406         *         null values, and the specified value is null
407         * @throws IllegalArgumentException if some property of this value
408         *         prevents it from being stored in the backing map
409         * @throws IllegalStateException implementations may, but are not
410         *         required to, throw this exception if the entry has been
411         *         removed from the backing map.
412         */
413        V setValue(V value);
414
415        /**
416         * Compares the specified object with this entry for equality.
417         * Returns <tt>true</tt> if the given object is also a map entry and
418         * the two entries represent the same mapping.  More formally, two
419         * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping
420         * if<pre>
421         *     (e1.getKey()==null ?
422         *      e2.getKey()==null : e1.getKey().equals(e2.getKey()))  &amp;&amp;
423         *     (e1.getValue()==null ?
424         *      e2.getValue()==null : e1.getValue().equals(e2.getValue()))
425         * </pre>
426         * This ensures that the <tt>equals</tt> method works properly across
427         * different implementations of the <tt>Map.Entry</tt> interface.
428         *
429         * @param o object to be compared for equality with this map entry
430         * @return <tt>true</tt> if the specified object is equal to this map
431         *         entry
432         */
433        boolean equals(Object o);
434
435        /**
436         * Returns the hash code value for this map entry.  The hash code
437         * of a map entry <tt>e</tt> is defined to be: <pre>
438         *     (e.getKey()==null   ? 0 : e.getKey().hashCode()) ^
439         *     (e.getValue()==null ? 0 : e.getValue().hashCode())
440         * </pre>
441         * This ensures that <tt>e1.equals(e2)</tt> implies that
442         * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries
443         * <tt>e1</tt> and <tt>e2</tt>, as required by the general
444         * contract of <tt>Object.hashCode</tt>.
445         *
446         * @return the hash code value for this map entry
447         * @see Object#hashCode()
448         * @see Object#equals(Object)
449         * @see #equals(Object)
450         */
451        int hashCode();
452
453        /**
454         * Returns a comparator that compares {@link Map.Entry} in natural order on key.
455         *
456         * <p>The returned comparator is serializable and throws {@link
457         * NullPointerException} when comparing an entry with a null key.
458         *
459         * @param  <K> the {@link Comparable} type of then map keys
460         * @param  <V> the type of the map values
461         * @return a comparator that compares {@link Map.Entry} in natural order on key.
462         * @see Comparable
463         * @since 1.8
464         */
465        public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
466            return (Comparator<Map.Entry<K, V>> & Serializable)
467                (c1, c2) -> c1.getKey().compareTo(c2.getKey());
468        }
469
470        /**
471         * Returns a comparator that compares {@link Map.Entry} by key using the given
472         * {@link Comparator}.
473         *
474         * <p>The returned comparator is serializable if the specified comparator
475         * is also serializable.
476         *
477         * @param  <K> the type of the map keys
478         * @param  <V> the type of the map values
479         * @param  cmp the key {@link Comparator}
480         * @return a comparator that compares {@link Map.Entry} by the key.
481         * @since 1.8
482         */
483        public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
484            Objects.requireNonNull(cmp);
485            return (Comparator<Map.Entry<K, V>> & Serializable)
486                (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
487        }
488    }
489
490    // Comparison and hashing
491
492    /**
493     * Compares the specified object with this map for equality.  Returns
494     * <tt>true</tt> if the given object is also a map and the two maps
495     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
496     * <tt>m2</tt> represent the same mappings if
497     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
498     * <tt>equals</tt> method works properly across different implementations
499     * of the <tt>Map</tt> interface.
500     *
501     * @param o object to be compared for equality with this map
502     * @return <tt>true</tt> if the specified object is equal to this map
503     */
504    boolean equals(Object o);
505
506    /**
507     * Returns the hash code value for this map.  The hash code of a map is
508     * defined to be the sum of the hash codes of each entry in the map's
509     * <tt>entrySet()</tt> view.  This ensures that <tt>m1.equals(m2)</tt>
510     * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
511     * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
512     * {@link Object#hashCode}.
513     *
514     * @return the hash code value for this map
515     * @see Map.Entry#hashCode()
516     * @see Object#equals(Object)
517     * @see #equals(Object)
518     */
519    int hashCode();
520
521    /**
522     * Performs the given action for each entry in this map until all entries
523     * have been processed or the action throws an exception.   Unless
524     * otherwise specified by the implementing class, actions are performed in
525     * the order of entry set iteration (if an iteration order is specified.)
526     * Exceptions thrown by the action are relayed to the caller.
527     *
528     * @implSpec
529     * The default implementation is equivalent to, for this {@code map}:
530     * <pre> {@code
531     * for (Map.Entry<K, V> entry : map.entrySet())
532     *     action.accept(entry.getKey(), entry.getValue());
533     * }</pre>
534     *
535     * The default implementation makes no guarantees about synchronization
536     * or atomicity properties of this method. Any implementation providing
537     * atomicity guarantees must override this method and document its
538     * concurrency properties.
539     *
540     * @param action The action to be performed for each entry
541     * @throws NullPointerException if the specified action is null
542     * @throws ConcurrentModificationException if an entry is found to be
543     * removed during iteration
544     * @since 1.8
545     */
546    default void forEach(BiConsumer<? super K, ? super V> action) {
547        Objects.requireNonNull(action);
548        for (Map.Entry<K, V> entry : entrySet()) {
549            K k;
550            V v;
551            try {
552                k = entry.getKey();
553                v = entry.getValue();
554            } catch(IllegalStateException ise) {
555                // this usually means the entry is no longer in the map.
556                throw new ConcurrentModificationException(ise);
557            }
558            action.accept(k, v);
559        }
560    }
561}
562