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